﻿Imports System.Text.RegularExpressions
Imports System.DirectoryServices

Public Class Form1
    Public ProjetCourant As New ClassProjet
    Public sProjetDefaut As String
    Public sProjetTemp As String
    Public DocumentCourant As ClassDocument
    Public oItemCourant As ListViewItem = Nothing
    Public iDocModif As Integer = 0
    Public iChaineTrouvee As Integer = 0
    Private PageNumber As Long
    Private DateImpression As String = ""
    Private ChercherSuivantIndex As Integer = 0
    Private m_nFirstCharOnPage As Integer
    Private PoliceDefaut As System.Drawing.Font

    Public Sub New()
        InitializeComponent()
    End Sub

#Region "Démarrage/Fermeture"
    'L'application démarre automatiquement avec le formulaire Form1...
    Private Sub Form1_Shown(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Shown
        SplashScreen.Show()
        My.Application.DoEvents()
        'Historique
        If My.Settings.WindowMaximized Then Me.WindowState = FormWindowState.Maximized
        Me.SplitContainer1.SplitterDistance = My.Settings.TailleVolet
        Me.RichTextBox1.Visible = False
        PoliceDefaut = Me.RichTextBox1.Font
        Me.OutilsToolStripMenuItem.Checked = Me.ToolStripOutils.Visible
        Me.Cursor = Cursors.WaitCursor
        'Création du répertoire des projets au besoin
        If My.Settings.DossierProjets = "" Then
            Dim sDossier As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\Projets scpEdit"
            If Not My.Computer.FileSystem.DirectoryExists(sDossier) Then
                Try
                    My.Computer.FileSystem.CreateDirectory(sDossier)
                    My.Settings.DossierProjets = sDossier
                Catch ex As Exception
                    MsgBox("Erreur à la création du répertoire par défaut pour les projets scpEdit: " & ex.Message)
                End Try
            End If
        End If
        SplashScreen.Close()
        'Chargement des fichiers passés en paramètres s'il y en a...
        Dim bChargesParam As Boolean = False
        For Each sParam As String In My.Application.CommandLineArgs()
            If My.Computer.FileSystem.FileExists(sParam) Then
                bChargesParam = True
                Me.OuvrirFichier(sParam)
            End If
        Next
        'Récupération des options
        Me.ReouvrirMenuItem.Checked = My.Settings.Reouvrir
        Me.RestreindreAuTexteMarqueToolStripMenuItem.Checked = My.Settings.RestreindreTransform
        Me.ConserverLesVersionsHistoriquesmax6ToolStripMenuItem.Checked = My.Settings.ConserverHistorique
        'Initialisation et chargement du projet courant
        sProjetDefaut = My.Application.Info.DirectoryPath & "\ProjetDefaut.scp"
        sProjetTemp = My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData & "\Projet.scp"
        If (Not bChargesParam) And My.Settings.Reouvrir And System.IO.File.Exists(My.Settings.ProjetOuvert) Then
            'On récupère le dernier projet ouvert
            ProjetCourant.Chemin = My.Settings.ProjetOuvert
        End If
        'On utilise le projet temporaire s'il n'y en a pas de spécifique ouvert
        If ProjetCourant.Chemin = "" Then
            ProjetCourant.Chemin = sProjetTemp
            'On récupère le projet par défaut au besoin
            If (Not My.Computer.FileSystem.FileExists(sProjetTemp)) And My.Computer.FileSystem.FileExists(sProjetDefaut) Then
                Try
                    My.Computer.FileSystem.CopyFile(sProjetDefaut, sProjetTemp)
                Catch ex As Exception
                    MsgBox("Erreur lors de la copie du modèle de projet par défaut: " & ex.Message)
                End Try
            End If
        End If
        LoadProjet(ProjetCourant, (Not bChargesParam) And My.Settings.Reouvrir)
        'Sélection du premier document comme document actif
        If Me.ListViewFichiers.Items.Count > 0 Then
            Me.ListViewFichiers.Items(0).Selected = True
            Me.AfficheCourant(Me.ListViewFichiers.Items(0))
        Else
            'On part avec un document vierge
            Call Me.Nouveau()
        End If
        'Mise à jour des résultats
        Call Me.UpdateCompteurs()
        'État des barres d'outils
        Me.ToolStripSplitButton1.Image = Me.ExpressionRégulièreToolStripMenuItem.Image
        Me.ToolStripSplitButton1.DefaultItem = Me.ExpressionRégulièreToolStripMenuItem
        Me.ToolStripSplitButton1.Text = Me.ExpressionRégulièreToolStripMenuItem.OwnerItem.Text & "\" & Me.ExpressionRégulièreToolStripMenuItem.Text
        'ToolStripManager.LoadSettings(Me, "scpEditDefaut")
        'Fichiers récents
        Call UpdateRecents()
        Call Me.UpdateTitreFen()
        My.Application.DoEvents()
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        'Fermeture de l'application
        'On force la mise à jour du document courant.
        If Not DocumentCourant Is Nothing Then DocumentCourant.Contenu = RichTextBox1.Text
        My.Settings.WindowMaximized = (Me.WindowState = FormWindowState.Maximized)
        My.Settings.TailleVolet = Me.SplitContainer1.SplitterDistance
        'Conserver les settings
        My.Settings.Reouvrir = Me.ReouvrirMenuItem.Checked
        My.Settings.RestreindreTransform = Me.RestreindreAuTexteMarqueToolStripMenuItem.Checked
        My.Settings.ConserverHistorique = Me.ConserverLesVersionsHistoriquesmax6ToolStripMenuItem.Checked
        My.Settings.Save()
        'Macro autoclose ?
        For Each oMacro As ClassMacro In ProjetCourant.ColCode
            If Commun.TestRegex(oMacro.Titre, "autoclose") Then
                oMacro.Execute()
                Exit For
            End If
        Next
        'On enregistre les documents modifiés ?
        For Each oItem As ListViewItem In Me.ListViewFichiers.Items
            Dim oDoc As ClassDocument = oItem.Tag
            If oDoc.Modifie Then
                Select Case MsgBox("Enregistrer les changements pour " & oDoc.Titre & "?", MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Question)
                    Case MsgBoxResult.Yes
                        Call Me.Enregistrer(oDoc)
                    Case MsgBoxResult.Cancel
                        e.Cancel = True
                        Exit Sub
                End Select
            End If
        Next
        SaveProjet(ProjetCourant)

        'ToolStripManager.SaveSettings(Me, "scpEditDefaut")
    End Sub

#End Region

#Region "Menus"

#Region "Menu Projet"

    Private Sub OuvrirProjetToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OuvrirProjetToolStripMenuItem1.Click
        Call OuvrirProjet()
    End Sub

    Private Sub EnregistrerProjetToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnregistrerProjetToolStripMenuItem1.Click
        Call EnregistrerProjet()
    End Sub

    Private Sub EnregistrerProjetSousToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnregistrerProjetSousToolStripMenuItem1.Click
        Call EnregistrerProjetSous()
    End Sub

    Private Sub FermerProjetToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FermerProjetToolStripMenuItem1.Click
        Call FermerProjet()
    End Sub

    Private Sub PropriétésToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PropriétésToolStripMenuItem.Click
        ProjetCourant.Edit(0)
    End Sub

    Private Sub ToolStripButton24_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton24.Click
        ProjetCourant.Edit(0)
    End Sub

    Private Sub PictureBoxProjet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBoxProjet.Click
        ProjetCourant.Edit(0)
    End Sub

    Private Sub LabelProjet_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LabelProjet.Click
        ProjetCourant.Edit(0)
    End Sub

 

#End Region

#Region "Menu Fichier"
 
    Private Sub CopierLeNomDuFichierCourantToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopierLeNomDuFichierCourantToolStripMenuItem1.Click
        Call CopierNomCourant()
    End Sub

    Private Sub CopierListeDesFichiersOuvertsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopierListeDesFichiersOuvertsToolStripMenuItem.Click
        Call Me.CopierNomsFichiersOuverts()
    End Sub

    Private Sub RécentsToolStripMenuItem_DropDownItemClicked(ByVal sender As Object, ByVal e As System.Windows.Forms.ToolStripItemClickedEventArgs) Handles RécentsToolStripMenuItem.DropDownItemClicked
        Call Me.OuvrirFichier(e.ClickedItem.Text)
    End Sub


    Private Sub CopierLesFichiersVersToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopierLesFichiersVersToolStripMenuItem.Click
        Call CopierVers(False)
    End Sub

    Private Sub CopierLesFichiersVersEtOuvrirToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopierLesFichiersVersEtOuvrirToolStripMenuItem.Click
        Call CopierVers(True)
    End Sub

    Private Sub ToolStripButtonRecharger_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonRecharger.Click
        Call Me.RechargerCourant()
    End Sub

    Private Sub VisualiserAvantImpressionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VisualiserAvantImpressionToolStripMenuItem.Click
        Call Me.Appercu()
    End Sub

    Private Sub OuvrirToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OuvrirToolStripMenuItem.Click
        Call Me.Ouvrir()
    End Sub

    Private Sub EnregistrerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnregistrerToolStripMenuItem.Click
        If Me.DocumentCourant IsNot Nothing Then
            Me.DocumentCourant.Contenu = Me.RichTextBox1.Text
            Call Me.Enregistrer(Me.DocumentCourant)
            Call Me.AfficherProprietes()
        End If
    End Sub

    Private Sub EnregistrerSousToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnregistrerSousToolStripMenuItem.Click
        Me.DocumentCourant.Contenu = Me.RichTextBox1.Text
        Call Me.EnregistrerSous(Me.DocumentCourant)
        Call Me.AfficherProprietes()
    End Sub

    Private Sub NouveauToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NouveauToolStripMenuItem.Click
        Call Me.Nouveau()
    End Sub

    Private Sub FermerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FermerToolStripMenuItem.Click
        Call Me.Fermer(Me.DocumentCourant)
        Call AfficherStatistiquesGlobales()
    End Sub

    Private Sub EnregistrerTousToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnregistrerTousToolStripMenuItem.Click
        Me.DocumentCourant.Contenu = Me.RichTextBox1.Text
        Call Me.EnregistrerTous()
        Call Me.AfficherProprietes()
    End Sub

    Private Sub FermerTousToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FermerTousToolStripMenuItem.Click
        Call Me.FermerTous()
    End Sub

    Private Sub FermerTousLesAutresToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FermerTousLesAutresToolStripMenuItem.Click
        Call Me.FermerTousSaufCourant()
    End Sub

    Private Sub ImprimerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImprimerToolStripMenuItem.Click
        Call Me.ImprimerCourant()
    End Sub

    Private Sub ImprimerTousToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImprimerTousToolStripMenuItem.Click
        Call Me.ImprimerTous()
    End Sub

    Private Sub FermerLesDocumentsSansMarquesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FermerLesDocumentsSansMarquesToolStripMenuItem.Click
        Call FermerSansMarques()
    End Sub

    Private Sub ChercherEtOuvrirToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ChercherEtOuvrirToolStripMenuItem.Click
        Call Chercher()
    End Sub

#End Region

#Region "Menu Édition"

    Private Sub CopierRTFToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopierRTFToolStripMenuItem.Click
        Call Me.CopierRTF()
    End Sub

    Private Sub DupliquerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DupliquerToolStripMenuItem.Click
        Call Me.Dupliquer()
    End Sub

    Private Sub AjouterToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AjouterToolStripMenuItem.Click
        Call Me.CopierAjouter()
    End Sub

    Private Sub MarqueurSuivantToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Call Me.AllerSuivant()
    End Sub

    Private Sub MarqueurPrécédentToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        Call Me.AllerPrecedent()
    End Sub

    Private Sub CopierToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopierToolStripMenuItem.Click
        Call Me.Copier()
    End Sub

    Private Sub CollerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CollerToolStripMenuItem.Click
        Call Me.Coller()
    End Sub

    Private Sub CouperToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CouperToolStripMenuItem.Click
        Call Me.Couper()
    End Sub

    Private Sub TransformerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TransformerToolStripMenuItem.Click
        Call Me.RemplacerTransformer()
    End Sub

    Private Sub AnnulerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AnnulerToolStripMenuItem.Click
        Call Me.Undo()
    End Sub

    Private Sub RefaireToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RefaireToolStripMenuItem.Click
        Call Me.Redo()
    End Sub

    Private Sub IndenterToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IndenterToolStripMenuItem.Click
        Call Me.IndentText(4)
    End Sub

    Private Sub ReculerDunNiveauToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReculerDunNiveauToolStripMenuItem.Click
        Call Me.IndentText(-4)
    End Sub

    Private Sub AtteindreLigneToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AtteindreLigneToolStripMenuItem.Click
        Call AtteindreLigne()
    End Sub

#End Region

#Region "Menu Insertion"

    Private Sub FragmentDeTexteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FragmentDeTexteToolStripMenuItem.Click
        Call Me.InsertFragment()
    End Sub


    Private Sub DateEtHeureToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateEtHeureToolStripMenuItem.Click
        Call InsererDateHeure()
    End Sub

    Private Sub DateToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateToolStripMenuItem.Click
        Call InsererDate()
    End Sub


    Private Sub UtilisateurToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UtilisateurToolStripMenuItem.Click
        Call InsererUtilisateur()
    End Sub

    Private Sub OrdinateurToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OrdinateurToolStripMenuItem.Click
        Call InsererComputer()
    End Sub

    Private Sub NomDeFichierToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NomDeFichierToolStripMenuItem.Click
        Call InsererNomFichier()
    End Sub

    Private Sub ContenuDunFichierToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ContenuDunFichierToolStripMenuItem.Click
        Call InsererFichier()
    End Sub

#End Region

#Region "Menu Outils"


    Private Sub ReformaterXmlToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReformaterXmlToolStripMenuItem.Click
        Call ReformaterXML()
    End Sub

    Private Sub ToolStripMenuItem8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem8.Click
        Calculer(False)
    End Sub

    Private Sub ToolStripMenuItem9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem9.Click
        Calculer(True)
    End Sub

    Private Sub ToolStripMenuItem10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem10.Click
        Call Fusion()
    End Sub


#End Region

#End Region

#Region "MenusContextuels"
    Private Sub DupliquerToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DupliquerToolStripMenuItem2.Click
        Call DupliquerMarqueurCourant()
    End Sub

    Private Sub DupliquerToolStripMenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DupliquerToolStripMenuItem3.Click
        Call DupliquerMarqueurCourant()
    End Sub


    Private Sub NouveauMarqueurToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NouveauMarqueurToolStripMenuItem.Click
        Call Me.AjouterAMarqueurs()
    End Sub

    Private Sub CollerToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CollerToolStripMenuItem1.Click
        Call Me.Coller()
    End Sub

    Private Sub CollerEnColonnesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CollerEnColonnesToolStripMenuItem.Click
        Call Me.CollerColonne()
    End Sub

    Private Sub DupliquerToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DupliquerToolStripMenuItem1.Click
        Call Me.Dupliquer()
    End Sub

    Private Sub SupprimerLigneToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerLigneToolStripMenuItem1.Click
        Call Me.DeleteLigne()
    End Sub

    Private Sub SupprimerColonneToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerColonneToolStripMenuItem1.Click
        Call Me.DeleteColonne()
    End Sub

    Private Sub RemplacerTransformerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RemplacerTransformerToolStripMenuItem.Click
        Call Me.RemplacerTransformer()
    End Sub

    Private Sub DateToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateToolStripMenuItem1.Click
        Call Me.InsererDate()
    End Sub

    Private Sub DateHeureToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DateHeureToolStripMenuItem.Click
        Call Me.InsererDateHeure()
    End Sub

    Private Sub UtilisateurToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UtilisateurToolStripMenuItem1.Click
        Call Me.InsererNomFichier()
    End Sub

    Private Sub FichiersToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FichiersToolStripMenuItem.Click
        Call Me.InsererFichier()
    End Sub

    Private Sub FragmentDeTexteToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FragmentDeTexteToolStripMenuItem1.Click
        Call Me.InsertFragment()
    End Sub

 
    Private Sub CollerEnColonneToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CollerEnColonneToolStripMenuItem.Click
        CollerColonne()
    End Sub

    Private Sub ToolStripButtonCollerColonne_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonCollerColonne.Click
        CollerColonne()
    End Sub

    Private Sub ExtractionSéparationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExtractionSéparationToolStripMenuItem.Click
        Call SeparationInteractif()
    End Sub

    Private Sub ToolStripButtonSupprimerLigne_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonSupprimerLigne.Click
        DeleteLigne()
    End Sub

    Private Sub ToolStripButtonSupprimerColonne_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonSupprimerColonne.Click
        DeleteColonne()
    End Sub

    Private Sub SupprimerLigneToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerLigneToolStripMenuItem.Click
        DeleteLigne()
    End Sub

    Private Sub SupprimerColonneToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerColonneToolStripMenuItem.Click
        DeleteColonne()
    End Sub

    Private Sub SuivantToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SuivantToolStripMenuItem.Click
        AllerSuivant()
    End Sub

    Private Sub PrécédentToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PrécédentToolStripMenuItem.Click
        AllerPrecedent()
    End Sub

    Private Sub MonterToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MonterToolStripMenuItem.Click
        Call RemonterMarqueur()
    End Sub

    Private Sub DescendreToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DescendreToolStripMenuItem.Click
        Call DescendreMarqueur()
    End Sub

    Private Sub NouveauToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NouveauToolStripMenuItem1.Click
        If Me.RichTextBox1.SelectionLength = 0 Then
            Call Me.NouveauMarqueur()
        Else
            Call Me.AjouterAMarqueurs()
        End If
    End Sub

    Private Sub ModifierToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ModifierToolStripMenuItem.Click
        Call EditMasqueCourant()
    End Sub

    Private Sub SupprimerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerToolStripMenuItem.Click
        Call Me.DeleteItemRecherche()
    End Sub

    Private Sub RaffraichirTousToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RaffraichirTousToolStripMenuItem.Click
        Call Me.RechercherMarqueurs()
    End Sub

    Private Sub EnregistrerToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnregistrerToolStripMenuItem1.Click
        Me.DocumentCourant.Contenu = Me.RichTextBox1.Text
        Call Me.Enregistrer(Me.DocumentCourant)
        Call Me.AfficherProprietes()
    End Sub

    Private Sub EnregistrerSousToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EnregistrerSousToolStripMenuItem1.Click
        Me.DocumentCourant.Contenu = Me.RichTextBox1.Text
        Call Me.EnregistrerSous(Me.DocumentCourant)
        Call Me.AfficherProprietes()
    End Sub

    Private Sub RechargerToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RechargerToolStripMenuItem1.Click
        Call RechargerCourant()
    End Sub

    Private Sub FermerToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FermerToolStripMenuItem1.Click
        Call Me.Fermer(Me.DocumentCourant)
        Call AfficherStatistiquesGlobales()
    End Sub

    Private Sub ImprimerToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImprimerToolStripMenuItem1.Click
        Call Me.ImprimerCourant()
    End Sub

    Private Sub AperçuToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AperçuToolStripMenuItem.Click
        Call Me.Appercu()
    End Sub

    Private Sub RafraichirTousToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RafraichirTousToolStripMenuItem.Click
        Call Me.RechercherMarqueurs()
    End Sub

    Private Sub NouveauToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NouveauToolStripMenuItem2.Click
        AllerSuivant()
    End Sub

    Private Sub AllerPrécédentToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AllerPrécédentToolStripMenuItem.Click
        AllerPrecedent()
    End Sub

    Private Sub NouveauToolStripMenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NouveauToolStripMenuItem3.Click
        If Me.RichTextBox1.SelectionLength = 0 Then
            Call Me.NouveauMarqueur()
        Else
            Call Me.AjouterAMarqueurs()
        End If
    End Sub

    Private Sub ModifierToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ModifierToolStripMenuItem1.Click
        Call EditMasqueCourant()
    End Sub

    Private Sub SupprimerToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerToolStripMenuItem1.Click
        Call Me.DeleteItemRecherche()
    End Sub

    Private Sub MonterToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MonterToolStripMenuItem1.Click
        Call RemonterMarqueur()
    End Sub

    Private Sub DescendreToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DescendreToolStripMenuItem1.Click
        DescendreMarqueur()
    End Sub


#End Region

#Region "Autres evenements"

    Private Sub ButtonSecurite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonSecurite.Click
        If DocumentCourant IsNot Nothing Then
            If DocumentCourant.Chemin <> "" Then
                FormBrowser.WebBrowser1.DocumentText = DocumentCourant.GetSecuriteXML(True)
                FormBrowser.ShowDialog()
            Else
                MsgBox("Le document courant n'est pas enregistré !", MsgBoxStyle.Exclamation)
            End If
        Else
            MsgBox("Cette fonction n'est disponible qu'avec un document ouvert !", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
        If DocumentCourant IsNot Nothing Then
            If DocumentCourant.Chemin <> "" Then
                FormBrowser.WebBrowser1.DocumentText = DocumentCourant.GetSecuriteXML(False)
                FormBrowser.ShowDialog()
            Else
                MsgBox("Le document courant n'est pas enregistré !", MsgBoxStyle.Exclamation)
            End If
        Else
            MsgBox("Cette fonction n'est disponible qu'avec un document ouvert !", MsgBoxStyle.Exclamation)
        End If
    End Sub
    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Call Me.AfficherStatistiquesGlobales()
        Clipboard.Clear()
        Clipboard.SetText(ExporterStatistiquesGlobales(), TextDataFormat.Text)
    End Sub

    Private Sub NumericUpDownZoom_ValueChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumericUpDownZoom.ValueChanged
        Me.RichTextBox1.ZoomFactor = CSng(Me.NumericUpDownZoom.Value / 100)
        If Not DocumentCourant Is Nothing Then DocumentCourant.ZoomFactor = Me.RichTextBox1.ZoomFactor
    End Sub

    Private Sub ListViewFichiers_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListViewFichiers.Resize
        Me.ListViewFichiers.Columns(0).Width = Me.ListViewFichiers.Width - Me.ListViewFichiers.Columns(1).Width - 10
    End Sub

    Private Sub ListViewMarqueurs_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListViewMarqueurs.DoubleClick
        Me.ListViewMarqueurs.SelectedItems(0).Checked = Not Me.ListViewMarqueurs.SelectedItems(0).Checked
        Call Me.EditMasqueCourant()
    End Sub

    Private Sub ListViewMarqueurs_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListViewMarqueurs.DragDrop
        If ListViewMarqueurs.SelectedItems.Count = 0 Then Exit Sub
        Dim p As Point = ListViewMarqueurs.PointToClient(New Point(e.X, e.Y))
        Dim dragToItem As ListViewItem = ListViewMarqueurs.GetItemAt(p.X, p.Y)
        If dragToItem Is Nothing Then Exit Sub
        Dim dragIndex As Integer = dragToItem.Index
        Dim i As Integer
        Dim sel(ListViewMarqueurs.SelectedItems.Count) As ListViewItem
        For i = 0 To ListViewMarqueurs.SelectedItems.Count - 1
            sel(i) = ListViewMarqueurs.SelectedItems.Item(i)
        Next
        For i = 0 To ListViewMarqueurs.SelectedItems.Count - 1
            Dim dragItem As ListViewItem = sel(i)
            Dim itemIndex As Integer = dragIndex
            If itemIndex = dragItem.Index Then Exit Sub
            If dragItem.Index < itemIndex Then
                itemIndex = itemIndex + 1
            Else
                itemIndex = dragIndex + i
            End If
            Dim insertItem As ListViewItem = CType(dragItem.Clone, ListViewItem)
            ListViewMarqueurs.Items.Insert(itemIndex, insertItem)
            ListViewMarqueurs.Items.Remove(dragItem)
        Next
    End Sub

    Private Sub ListViewMarqueurs_DragEnter(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles ListViewMarqueurs.DragEnter
        Dim i As Integer
        For i = 0 To e.Data.GetFormats().Length - 1
            If e.Data.GetFormats()(i).Equals("System.Windows.Forms.ListView+SelectedListViewItemCollection") Then
                e.Effect = DragDropEffects.Move
            End If
        Next
    End Sub

    Private Sub ListViewMarqueurs_ItemChecked(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemCheckedEventArgs) Handles ListViewMarqueurs.ItemChecked
        'If Me.DocumentCourant IsNot Nothing Then Call Me.RechercherCourant()
    End Sub

    Private Sub ListViewMarqueurs_ItemDrag(ByVal sender As Object, ByVal e As System.Windows.Forms.ItemDragEventArgs) Handles ListViewMarqueurs.ItemDrag
        'Initier le drag de l'item courant avec un move
        ListViewMarqueurs.DoDragDrop(ListViewMarqueurs.SelectedItems, DragDropEffects.Move)
    End Sub

    Private Sub ListViewMarqueurs_Resize(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListViewMarqueurs.Resize
        Me.ListViewMarqueurs.Columns(0).Width = Me.ListViewMarqueurs.Width - Me.ListViewMarqueurs.Columns(1).Width - 10
    End Sub

    Private Sub ListViewFichiers_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListViewFichiers.Click
        AjouterHistoriqueMacro("scpEdit.SelectFichier(" & Chr(34) & Me.DocumentCourant.Chemin & Chr(34) & ")")
        Call AfficheCourant(Me.ListViewFichiers.SelectedItems(0))
    End Sub

    Private Sub ButtonAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If Me.RichTextBox1.SelectionLength = 0 Then
            Call Me.NouveauMarqueur()
        Else
            Call Me.AjouterAMarqueurs()
        End If
    End Sub

    Private Sub TextBoxRecherche_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If e.KeyChar = Chr(13) Then
            Call Me.NouveauMarqueur()
        End If
    End Sub

    Private Sub RichTextBox1_DragDrop(ByVal sender As Object, ByVal e As System.Windows.Forms.DragEventArgs) Handles RichTextBox1.DragDrop
        If e.Data.GetDataPresent(DataFormats.FileDrop) Then
            Dim sFileNames As String() = e.Data.GetData(DataFormats.FileDrop)
            For Each sFileName As String In sFileNames
                OuvrirFichier(sFileName)
            Next
            e.Effect = DragDropEffects.None
        ElseIf Not e.Data.GetDataPresent("Text", False) Then
            e.Effect = DragDropEffects.None
        End If
    End Sub


    Private Sub RichTextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles RichTextBox1.KeyDown
        'Touches à traiter à priori
        Select Case e.KeyCode
            Case Keys.Tab
                'traitement à venir
                Call Me.InsertTab()
                e.Handled = True
                e.SuppressKeyPress = True
            Case Keys.Enter
                'Exécution commande live
                If e.Shift Then Call Me.InsererShell()
                If e.Control Then Call Me.InsererPowerShell()
                If e.Alt Then Call Me.InsererCode()
                'Indentation automatique
                Dim iPos As Integer = Me.RichTextBox1.GetFirstCharIndexOfCurrentLine
                If iPos < Me.RichTextBox1.TextLength Then
                    Dim iCount As Integer = 0
                    While Me.RichTextBox1.Text(iPos + iCount) = " "
                        iCount += 1
                    End While
                    Me.RichTextBox1.SelectedText = vbCrLf & Space(iCount)
                    e.SuppressKeyPress = True
                End If
            Case Keys.Oemplus
                If e.Control Then
                    Calculer(True)
                    e.SuppressKeyPress = True
                End If
                If e.Alt Then
                    Calculer(False)
                    e.SuppressKeyPress = True
                End If
        End Select
    End Sub

    Private Sub RichTextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles RichTextBox1.KeyPress
        'Signaler les parenthèses fermantes
        If e.KeyChar = ")" Then
            Dim iPos As Integer = Me.RichTextBox1.SelectionStart
            Dim iNbFermantes As Integer = 1
            While iPos > 0 And iNbFermantes > 0
                iPos -= 1
                If Me.RichTextBox1.Text(iPos) = ")" Then iNbFermantes += 1
                If Me.RichTextBox1.Text(iPos) = "(" Then iNbFermantes -= 1
            End While
            If Me.RichTextBox1.Text(iPos) = "(" Then
                Dim iOldLen As Integer = Me.RichTextBox1.SelectionLength
                Dim iOldPos As Integer = Me.RichTextBox1.SelectionStart
                Me.RichTextBox1.SelectionStart = iPos
                Me.RichTextBox1.SelectionLength = 1
                System.Threading.Thread.Sleep(500)
                Me.RichTextBox1.SelectionStart = iOldPos
                Me.RichTextBox1.SelectionLength = iOldLen
            End If
        End If
    End Sub

    Private Sub RichTextBox1_KeyUp(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles RichTextBox1.KeyUp
        'Touches ne pouvant pas être capturées à priori et donc traitées après coup
        'On fait une gestion manuelle plutôt qu'une gestion automatique par le contrôle
        'RichTextBox1 pour éviter de coller le texte rtf...
        If e.Control Then
            e.SuppressKeyPress = True
            Select Case e.KeyCode
                Case Keys.Delete
                    Call Me.SupprimerMarqueCourant()
                Case Keys.E
                    Call Me.RetourCourant()
                Case Keys.V
                    'BUG - Pas moyen de supprimer le keypress de control v. Le richtextbox le handle toujours...
                    'Call Me.Coller()
                Case Keys.X
                    Call Me.Couper()
                Case Keys.C
                    My.Application.DoEvents()
                    Call Me.Copier()
                Case Keys.K
                    Call Me.CopierRTF()
                Case Keys.Z
                    Call Me.Undo()
                Case Keys.R
                    Call Me.Redo()
                Case Keys.T
                    Call Me.RemplacerTransformer()
                Case Keys.M
                    Call Me.AjouterAMarqueurs()
                Case Keys.A
                    Me.RichTextBox1.SelectAll()
                Case Keys.L
                    Call Me.AtteindreLigne()
                Case Keys.D
                    Call Me.Dupliquer()
                Case Keys.J
                    Call Me.CopierAjouter()
                Case Keys.P
                    Call ImprimerCourant()
                Case Keys.Y
                    Call DeleteLigne()
                Case Keys.U
                    Call DeleteColonne()
                Case Keys.Q
                    Call CollerColonne()
                Case Keys.N
                    Call InsererTexteMarqueur()
                Case Keys.O
                    Call OuvrirFichiersSelection()
                Case Keys.F
                    Call InsererFinTag()
                Case Else
                    e.Handled = False
                    e.SuppressKeyPress = False
            End Select
        End If
    End Sub

    Private Sub RichTextBox1_MouseDoubleClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles RichTextBox1.MouseDoubleClick
        Me.ToolStripTextBoxRec.Text = Me.RichTextBox1.SelectedText.Trim()
    End Sub

    Private Sub RichTextBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.SelectionChanged
        If Me.RichTextBox1.Visible Then
            Me.ToolStripStatusLabelSel.Text = "Sel " & Me.RichTextBox1.SelectionLength.ToString("0")
            Me.ToolStripStatusLabelPos.Text = "Pos " & GetLigne() + 1 & "," & GetColonne() + 1
        End If
    End Sub

    Private Sub RichTextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles RichTextBox1.TextChanged
        If Me.RichTextBox1.Visible Then
            'Ajuster les menu Undo/redo
            Call Me.AjusterMenus()
            'Ajuster les infos sur le fichiers
            Me.LabelTexteLignes.Text = Me.RichTextBox1.Lines.Count.ToString("0")
            Me.LabelTexteLongueur.Text = Me.RichTextBox1.TextLength.ToString("0")
        End If
    End Sub

    Public Sub UpdateTitreFen()
        Me.Text = My.Application.Info.ProductName & ": "
        If ProjetCourant.Titre <> "" Then Me.Text &= ProjetCourant.Titre
        If Not Me.DocumentCourant Is Nothing Then
            If ProjetCourant.Titre <> "" Then Me.Text &= " -"
            Me.Text &= " " & DocumentCourant.Titre
        End If
        Me.LabelProjet.Text = ProjetCourant.Titre
        Me.PictureBoxProjet.Visible = (ProjetCourant.Titre <> "")
    End Sub

#End Region

#Region "ToolStrip"
    Private Sub ActualiserLesMarqueursToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ActualiserLesMarqueursToolStripMenuItem.Click
        Me.RichTextBox1.Visible = False
        Call Me.RechercherMarqeursDocCourant()
        Me.RichTextBox1.Visible = True
    End Sub

    Private Sub SéparerLesLignesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SéparerLesLignesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.SeparerLignes)
    End Sub

    Private Sub SéparerLesLignesToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SéparerLesLignesToolStripMenuItem1.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.SeparerLignes)
    End Sub

    Private Sub ScriptToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ScriptToolStripMenuItem1.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.ScriptRemplacement)
    End Sub

    Private Sub ScriptToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ScriptToolStripMenuItem2.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.ScriptRemplacement)
    End Sub

    Private Sub SupprimerToolStripMenuItem3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerToolStripMenuItem3.Click
        Call SupprimerCourant(Me.DocumentCourant)
    End Sub

    Private Sub FusionnerLesLignesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FusionnerLesLignesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.FusionnerLignes)
    End Sub

    Private Sub FusionnerLesLignesToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FusionnerLesLignesToolStripMenuItem1.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.FusionnerLignes)
    End Sub

    Private Sub PremièreLettreEnMajusculeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PremièreLettreEnMajusculeToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.PremiereLettre)
    End Sub

    Private Sub PremièreLettreEnMajusculeToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PremièreLettreEnMajusculeToolStripMenuItem1.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.PremiereLettre)
    End Sub

    Private Sub PivoterAutourDuSymboleToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PivoterAutourDuSymboleToolStripMenuItem1.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Pivoter)
    End Sub

    Private Sub ToolStripButton20_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton20.Click
        Call Me.Fusion()
    End Sub

    Private Sub ToolStripButton21_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton21.Click
        Call Me.SeparationInteractif()
    End Sub

    Private Sub ToolStripButton22_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton22.Click
        Call Me.Undo()
    End Sub

    Private Sub ToolStripButton23_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton23.Click
        Call Me.Redo()
    End Sub

    Private Sub CopierToolStripMenuItemCopier1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopierToolStripMenuItemCopier1.Click
        Call Copier()
    End Sub

    Private Sub OuvrirListeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OuvrirListeToolStripMenuItem.Click
        Call Me.OuvrirListe()
    End Sub
    Private Sub MajusculesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MajusculesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Majuscules)
    End Sub

    Private Sub ExpressionRégulièreToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExpressionRégulièreToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.RemplacerRegEx)
    End Sub

    Private Sub TexteToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TexteToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.RemplacerTexte)
    End Sub

    Private Sub TableDeCaractèresToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TableDeCaractèresToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.RemplacerTableCar)
    End Sub

    Private Sub AlignerLesVirgulesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AlignerLesVirgulesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.AlignerEgal)
    End Sub

    Private Sub AlignerLesPointsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AlignerLesPointsToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.AlignerPonctuation)
    End Sub

    Private Sub AlignerAutreToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AlignerAutreToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Aligner)
    End Sub

    Private Sub CaractèresSpéciauxVersÉchapementUnicodeToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CaractèresSpéciauxVersÉchapementUnicodeToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.CarUnicode)
    End Sub

    Private Sub ÉchapementUnicodeuxxxxVersCaractèreSpéciauxToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ÉchapementUnicodeuxxxxVersCaractèreSpéciauxToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.UnicodeCar)
    End Sub

    Private Sub MinusculesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MinusculesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Minuscules)
    End Sub

    Private Sub ToolStripMenuItem21_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem21.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.MettreEspacesEnColonnes)
    End Sub

    Private Sub AligneEnColonnesSelonVirgulesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AligneEnColonnesSelonVirgulesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.MettreVirgulesEnColonnes)
    End Sub

    Private Sub MettreEnColonnesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MettreEnColonnesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.MettreEnColonnes)
    End Sub

    Private Sub ToolStripMenuItem22_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem22.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Justifier)
    End Sub

    Private Sub ReformaterEnLargeurToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ReformaterEnLargeurToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.AjusterLargeur)
    End Sub

    Private Sub SupprimerLesDoublesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerLesDoublesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.SupprimerDoubles)
    End Sub

    Private Sub ConvertirLignesEnListeAvecVirgulesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConvertirLignesEnListeAvecVirgulesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.LignesListe)
    End Sub

    Private Sub ConvertirListeAvecVirgulesEnLignesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConvertirListeAvecVirgulesEnLignesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.ListeLignes)
    End Sub

    Private Sub SupprimerLesEspacesAvantToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerLesEspacesAvantToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.TrimAvant)
    End Sub

    Private Sub SupprimerLesEspacesAprèsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerLesEspacesAprèsToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.TrimApres)
    End Sub

    Private Sub SupprimerLesEspacesEnAvantEtAprèstrimToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerLesEspacesEnAvantEtAprèstrimToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Trim)
    End Sub

    Private Sub EncadrerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles EncadrerToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Encadrer)
    End Sub

    Private Sub TrierLesLignesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrierLesLignesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.TrierLignes)
    End Sub

    Private Sub TrierLesColonnesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrierLesColonnesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.TrierEspaces)
    End Sub

    Private Sub TrierSelonVirgulesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrierSelonVirgulesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.TrierVirgules)
    End Sub

    Private Sub ToolStripMenuItem23_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem23.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Trier)
    End Sub

    Private Sub RetirerLesAccentsFrançaisToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RetirerLesAccentsFrançaisToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.EnleverAccents)
    End Sub

    Private Sub ToolStripMenuItem24_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem24.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.RemplacerTexte)
    End Sub

    Private Sub ToolStripMenuItem25_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem25.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.RemplacerRegEx)
    End Sub

    Private Sub ToolStripMenuItem26_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem26.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.RemplacerTableCar)
    End Sub

    Private Sub ToolStripMenuItem28_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem28.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.AlignerEgal)
    End Sub

    Private Sub ToolStripMenuItem29_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem29.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.AlignerPonctuation)
    End Sub

    Private Sub ToolStripMenuItem30_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem30.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Aligner)
    End Sub

    Private Sub ToolStripMenuItem31_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem31.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.CarUnicode)
    End Sub

    Private Sub ToolStripMenuItem32_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem32.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.UnicodeCar)
    End Sub

    Private Sub ToolStripMenuItem33_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem33.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.EnleverAccents)
    End Sub

    Private Sub ToolStripMenuItem35_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem35.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Majuscules)
    End Sub

    Private Sub ToolStripMenuItem36_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem36.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Minuscules)
    End Sub

    Private Sub ToolStripMenuItem38_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem38.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.MettreEspacesEnColonnes)
    End Sub

    Private Sub ToolStripMenuItem39_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem39.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.MettreVirgulesEnColonnes)
    End Sub

    Private Sub ToolStripMenuItem40_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem40.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.MettreEnColonnes)
    End Sub

    Private Sub ToolStripMenuItem42_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem42.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Justifier)
    End Sub

    Private Sub ToolStripMenuItem43_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem43.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.AjusterLargeur)
    End Sub

    Private Sub ToolStripMenuItem44_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem44.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.SupprimerDoubles)
    End Sub

    Private Sub ToolStripMenuItem45_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem45.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.LignesListe)
    End Sub

    Private Sub ToolStripMenuItem46_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem46.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.ListeLignes)
    End Sub

    Private Sub ToolStripMenuItem48_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem48.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.TrierLignes)
    End Sub

    Private Sub ToolStripMenuItem49_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem49.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.TrierEspaces)
    End Sub

    Private Sub ToolStripMenuItem50_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem50.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.TrierVirgules)
    End Sub

    Private Sub ToolStripMenuItem51_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem51.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Trier)
    End Sub

    Private Sub ToolStripMenuItem53_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem53.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.TrimAvant)
    End Sub

    Private Sub ToolStripMenuItem54_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem54.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.TrimApres)
    End Sub

    Private Sub ToolStripMenuItem55_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem55.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Trim)
    End Sub

    Private Sub ToolStripMenuItem57_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem57.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Encadrer)
    End Sub

    Private Sub SupprimerLignesVidesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerLignesVidesToolStripMenuItem.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.SupprimerLignesVides)
    End Sub

    Private Sub ToolStripMenuItem58_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem58.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.SupprimerLignesVides)
    End Sub

    Private Sub ToolStripButton2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton2.Click
        Call OuvrirProjet()
    End Sub

    Private Sub ToolStripButton3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton3.Click
        Call EnregistrerProjet()

    End Sub

    Private Sub ToolStripButton4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton4.Click
        Call EnregistrerProjetSous()
    End Sub

    Private Sub ToolStripButton5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton5.Click
        Call FermerProjet()
    End Sub

    Private Sub ToolStripButton6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton6.Click
        Call Me.InsererDate()
    End Sub

    Private Sub ToolStripButton7_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton7.Click
        Call Me.InsererDateHeure()
    End Sub

    Private Sub ToolStripButton8_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton8.Click
        Call Me.InsererUtilisateur()
    End Sub

    Private Sub ToolStripButton9_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton9.Click
        Call Me.InsererNomFichier()
    End Sub

    Private Sub ToolStripButton10_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton10.Click
        Call Me.InsererComputer()
    End Sub

    Private Sub ToolStripButton11_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton11.Click
        Call Me.InsererFichier()

    End Sub

    Private Sub ToolStripButton13_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton13.Click
        Call Me.InsertFragment()
    End Sub

    Private Sub ToolStripButton14_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton14.Click
        Call Me.RemplacerTransformer()
    End Sub

    Private Sub ToolStripButton15_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton15.Click
        Call AllerPrecedent()
    End Sub

    Private Sub ToolStripButton16_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton16.Click
        Call AllerSuivant()
    End Sub

    Private Sub ToolStripButton17_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton17.Click
        Call Me.RechercherMarqueurs()
    End Sub


    Private Sub ToolStripButton18_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton18.Click
        If Me.ListViewFichiers.SelectedItems.Count > 0 Then Me.ChercherSuivantIndex = Me.ListViewFichiers.SelectedIndices(0)
        Call ChercherSuivant()
    End Sub

    Private Sub ToolStripButton19_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton19.Click
        Call Me.AtteindreLigne()
    End Sub

    Private Sub ToolStripTextBoxRec_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs)
        If e.KeyChar = Chr(13) Then Call Me.ChercherSuivant()
    End Sub

    Private Sub ToolStripButtonCopyRTF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonCopyRTF.Click
        Call Me.CopierRTF()
    End Sub

    Private Sub ToolStripButtonDupliquer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonDupliquer.Click
        Call Me.Dupliquer()
    End Sub

    Private Sub ToolStripButtonCopierAjouter_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonCopierAjouter.Click
        Call Me.CopierAjouter()
    End Sub

    Private Sub RechargerToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RechargerToolStripMenuItem.Click
        Call RechargerCourant()
    End Sub

    Private Sub ToolStripButtonFermerAutres_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonFermerAutres.Click
        Call Me.FermerTousSaufCourant()
    End Sub

    Private Sub ToolStripButtonFermerSansMarque_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonFermerSansMarque.Click
        Call Me.FermerSansMarques()
    End Sub

    Private Sub ToolStripButtonAppercu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonAppercu.Click
        Call Me.Appercu()
    End Sub

    Private Sub ToolStripButtonImprTous_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonImprTous.Click
        Call Me.ImprimerTous()
    End Sub

    Private Sub ToolStripButtonDroite_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonDroite.Click
        Call Me.IndentText(4)
    End Sub

    Private Sub ToolStripButtonGauche_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonGauche.Click
        Call Me.IndentText(-4)
    End Sub

    Private Sub ToolStripButtonFormatXML_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonFormatXML.Click
        Call ReformaterXML()
    End Sub
    Private Sub ToolStripButtonCalcInsert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonCalcInsert.Click
        Calculer(True)
    End Sub

    Private Sub ToolStripButtonCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonCalc.Click
        Calculer(False)
    End Sub

    Private Sub ToolStripButtonAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonAbout.Click
        AboutBox.ShowDialog()
    End Sub

    Private Sub ToolStripButtonChercherOuvrir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonChercherOuvrir.Click
        Call Chercher()
    End Sub
    Private Sub ToolStripButtonNouveau_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonNouveau.Click
        Call Me.Nouveau()
    End Sub

    Private Sub ToolStripButtonOuvrir_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonOuvrir.Click
        Call Me.Ouvrir()
    End Sub

    Private Sub ToolStripButtonEnrg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonEnrg.Click
        Me.DocumentCourant.Contenu = Me.RichTextBox1.Text
        Call Me.Enregistrer(Me.DocumentCourant)
        Call Me.AfficherProprietes()
    End Sub

    Private Sub ToolStripButton1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton1.Click
        Me.DocumentCourant.Contenu = Me.RichTextBox1.Text
        Call Me.EnregistrerSous(Me.DocumentCourant)
        Call Me.AfficherProprietes()
    End Sub

    Private Sub ToolStripButtonEnrgTous_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonEnrgTous.Click
        Call Me.EnregistrerTous()
        Call Me.AfficherProprietes()
    End Sub

    Private Sub ToolStripButtonClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonClose.Click
        Call Me.Fermer(Me.DocumentCourant)
        Call AfficherStatistiquesGlobales()
    End Sub

    Private Sub ToolStripButtonFermerTous_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonFermerTous.Click
        Call Me.FermerTous()
    End Sub

    Private Sub ToolStripButtonImprimer_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonImprimer.Click
        Call Me.ImprimerCourant()
    End Sub

    Private Sub ToolStripButtonCouper_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonCouper.Click
        Call Me.Couper()
    End Sub

    Private Sub ToolStripButtonCopier_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonCopier.Click
        Call Me.Copier()
    End Sub

    Private Sub ToolStripButtonColler_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonColler.Click
        Call Me.Coller()
    End Sub

#End Region

#Region "Fichiers"
    Public Sub CopierNomCourant()
        If DocumentCourant IsNot Nothing Then
            Clipboard.Clear()
            If DocumentCourant.Chemin = "" Then
                Clipboard.SetText(DocumentCourant.Titre, TextDataFormat.Text)
            Else
                Clipboard.SetText(DocumentCourant.Chemin, TextDataFormat.Text)
            End If

        End If

        AjouterHistoriqueMacro("scpEdit.CopierNomCourant()")
    End Sub

    Public Sub CopierNomsFichiersOuverts()
        Clipboard.Clear()
        If ListViewFichiers.Items.Count > 0 Then
            Dim sTexte As String = ""
            For Each oItem As ListViewItem In Me.ListViewFichiers.Items
                If oItem.Tag.Chemin = "" Then
                    sTexte &= oItem.Tag.Titre & vbCrLf
                Else
                    sTexte &= oItem.Tag.Chemin & vbCrLf
                End If
            Next
            Clipboard.SetText(sTexte)
        End If

        AjouterHistoriqueMacro("scpEdit.CopierNomsFichiersOuverts()")
    End Sub

    Private Sub RetourCourant()
        'Réinitialiser le document courant
        If DocumentCourant IsNot Nothing Then
            Me.RichTextBox1.Visible = False
            DocumentCourant.Contenu = Me.RichTextBox1.Text
            DocumentCourant.RetourArriere()
            Me.RichTextBox1.Text = DocumentCourant.Contenu
            Call Me.RechercherMarqeursDocCourant()
            DocumentCourant.ContenuRTF = Me.RichTextBox1.Rtf
            AfficherStatistiquesGlobales()
            AfficherProprietes()
            Me.RichTextBox1.Visible = True
            AjouterHistoriqueMacro("'Fonction interactive non automatisable: Retour à une version antérieure")
        End If
    End Sub

    Public Sub ResetCourant()
        'Réinitialiser le document courant
        If DocumentCourant IsNot Nothing Then
            DocumentCourant.RetourArriere()
            Me.RichTextBox1.Text = DocumentCourant.Contenu
            Call Me.RechercherMarqeursDocCourant()
            DocumentCourant.ContenuRTF = Me.RichTextBox1.Rtf
            AfficherProprietes()
        End If

        AjouterHistoriqueMacro("scpEdit.AnnulerTout")
    End Sub

    Public Sub CopierVersAuto(ByVal CheminDossier As String, ByVal bFermer As Boolean)
        'Version non-interractive, overwrite
        If My.Computer.FileSystem.DirectoryExists(CheminDossier) Then
            Me.ToolStripProgressBar1.Minimum = 1
            Me.ToolStripProgressBar1.Maximum = Me.ListViewFichiers.Items.Count + 1
            Me.ToolStripProgressBar1.Value = 1
            Me.ToolStripProgressBar1.Visible = True
            For Each oItem As ListViewItem In Me.ListViewFichiers.Items
                Dim oDoc As ClassDocument = oItem.Tag
                Dim sNouveau As String = CheminDossier & "\" & System.IO.Path.GetFileName(oDoc.Chemin)
                If sNouveau.ToLower <> oDoc.Chemin.ToLower Then
                    My.Computer.FileSystem.CopyFile(oDoc.Chemin, sNouveau, True)
                    If bFermer Then Call Me.Fermer(oDoc)
                    Call OuvrirFichier(sNouveau)
                End If
            Next
            Me.ToolStripProgressBar1.Visible = False
        End If
    End Sub

    Private Sub CopierVers(ByVal bFermer As Boolean)
        Me.FolderBrowserDialog1.Description = "Copier les fichiers ouverts vers l'emplacement suivant:"
        Me.FolderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer
        If Me.FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Me.ToolStripProgressBar1.Minimum = 1
            Me.ToolStripProgressBar1.Maximum = Me.ListViewFichiers.Items.Count + 1
            Me.ToolStripProgressBar1.Value = 1
            Me.ToolStripProgressBar1.Visible = True
            FormErreur.Reset()
            FormErreur.Text = "Copier les fichiers ouverts"
            DocumentCourant.Contenu = Me.RichTextBox1.Text
            DocumentCourant.ContenuRTF = Me.RichTextBox1.Rtf
            For Each oItem As ListViewItem In Me.ListViewFichiers.Items
                Dim oDoc As ClassDocument = oItem.Tag
                If oDoc.Chemin <> "" Then
                    If oDoc.Modifie Then oDoc.Enregistrer()
                    Dim sNouveau As String = Me.FolderBrowserDialog1.SelectedPath & "\" & System.IO.Path.GetFileName(oDoc.Chemin)
                    If sNouveau.ToLower <> oDoc.Chemin.ToLower Then
                        My.Computer.FileSystem.CopyFile(oDoc.Chemin, sNouveau, FileIO.UIOption.AllDialogs)
                        If bFermer Then Call Fermer(oDoc)
                        Call Me.OuvrirFichier(sNouveau)
                    Else
                        FormErreur.AjouteErreur("Le fichier " & oDoc.Chemin & " ne peut être copié sur lui-même!")
                    End If
                End If
            Next
            Me.ToolStripProgressBar1.Visible = False
            FormErreur.ShowSiErreur()
            AjouterHistoriqueMacro("scpEdit.CopierVers(" & Chr(34) & Me.FolderBrowserDialog1.SelectedPath & Chr(34) & "," & bFermer & ")")
        End If
    End Sub

    Public Sub OuvrirListeAuto(ByVal sListeName As String)
        'Ouvrir les fichiers identifiés par une liste
        'On des fichiers à ouvrir

        Const sRegexFull As String = "(([a-z]:)|(\\\\[^<>:""/\\\?\*\.\r\n]+(\\[^<>:""/\\\?\*\.\r\n]+)))(\\[^<>:""/\\\?\*\.\r\n]+)+(\.[^<>:""/\\\?\*\.\r\n\s]+)+"
        Dim sArgs As String = My.Computer.FileSystem.ReadAllText(sListeName)
        FormOuvrirListe.Reset()
        'On boucle sur tous les noms de fichiers complet
        For Each oMatch As System.Text.RegularExpressions.Match In System.Text.RegularExpressions.Regex.Matches(sArgs, sRegexFull, RegexOptions.IgnoreCase Or RegexOptions.Multiline)
            FormOuvrirListe.AjouterFichierSiExiste(oMatch.Value)
        Next
        Me.RichTextBox1.Visible = False
        Me.Cursor = Cursors.WaitCursor
        If FormOuvrirListe.ShowSiFichiers() = Windows.Forms.DialogResult.OK Then
            For Each oItem As ListViewItem In FormOuvrirListe.ListView1.CheckedItems()
                OuvrirFichier(oItem.Text)
            Next
        End If
        If Not Me.DocumentCourant Is Nothing Then Me.RichTextBox1.Visible = True
        Me.Cursor = Cursors.Default
        Call AfficherStatistiquesGlobales()
        Me.TabControl1.SelectedTab = Me.TabPageEdition
        AjouterHistoriqueMacro("scpEdit.OuvrirListe(" & Chr(34) & sListeName & Chr(34) & ")")
    End Sub

    Public Sub OuvrirListe()
        'Ouvrir les fichiers identifiés par une liste
        'Version interactive avec confirmation via une liste à cocher
        Me.OpenFileDialog1.Filter = "Tous|*.*|Texte|*.txt"
        Me.OpenFileDialog1.DefaultExt = "Tous"
        Me.OpenFileDialog1.Title = "Ouvrir les fichiers d'une liste"
        Me.OpenFileDialog1.Multiselect = False
        If My.Settings.DernierDossier <> "" Then Me.OpenFileDialog1.InitialDirectory = My.Settings.DernierDossier
        Me.OpenFileDialog1.FileName = ""
        If Me.OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            OuvrirListeAuto(Me.OpenFileDialog1.FileName())
        End If
    End Sub

    Public Sub Enregistrer(ByVal oDocument As ClassDocument)
        'Enregistrer le document spécifié
        If Not oDocument Is Nothing Then
            If oDocument.Chemin = "" Then
                'Nouveau document jamais enregistré
                Me.EnregistrerSous(oDocument)
            Else
                'Ok, on enregistre avec le nom actuel
                oDocument.Enregistrer()
                AjouterHistoriqueMacro("scpEdit.EnregistrerFichier")
            End If
            Me.RichTextBox1.Visible = False
            RechercherMarqeursDocCourant()
            Me.RichTextBox1.Visible = True
        End If
    End Sub

    Public Sub EnregistrerSous(ByVal oDocument As ClassDocument)
        'Enregistrer le document spécifié en demandant un nouveau nom à l'utilisateur
        If Not oDocument Is Nothing Then
            oDocument.Contenu = Me.RichTextBox1.Text
            Me.SaveFileDialog1.Filter = "Texte|*.txt|Journaux|*.log|Tous|*.*"
            Me.SaveFileDialog1.Title = "Enregistrer " & oDocument.Titre & " sous..."
            Me.SaveFileDialog1.OverwritePrompt = True
            If My.Settings.DernierDossier <> "" Then Me.SaveFileDialog1.InitialDirectory = My.Settings.DernierDossier
            If Me.SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then EnregistrerSous(oDocument, Me.SaveFileDialog1.FileName)
        End If
    End Sub

    Public Function GetNewFileName(ByVal Filter As String) As String
        Me.SaveFileDialog1.Filter = "Texte|*.txt|Journaux|*.log|Tous|*.*"
        If Filter <> "" Then Me.SaveFileDialog1.Filter = Filter
        Me.SaveFileDialog1.Title = "Enregistrer sous..."
        Me.SaveFileDialog1.OverwritePrompt = True
        If My.Settings.DernierDossier <> "" Then Me.SaveFileDialog1.InitialDirectory = My.Settings.DernierDossier
        If Me.SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Return Me.SaveFileDialog1.FileName
        Else
            Return ""
        End If
    End Function

    Public Function GetFolderName() As String
        If My.Settings.DernierDossier <> "" Then Me.FolderBrowserDialog1.RootFolder = My.Settings.DernierDossier
        If Me.FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Return Me.FolderBrowserDialog1.SelectedPath
        Else
            Return ""
        End If
    End Function

    Public Sub EnregistrerSous(ByVal oDocument As ClassDocument, ByVal CheminFichier As String)
        'On a un nom de fichier
        'On conserve le dossier pour la prochaine fois...
        My.Settings.DernierDossier = My.Computer.FileSystem.GetParentPath(CheminFichier)
        'On affiche le nom du document dans la barre titre de la fenêtre
        Call UpdateTitreFen()
        'On enregistre le document
        Call oDocument.EnregistrerSous(CheminFichier)
        'On retire le document courant de la liste et on le réinsère pour forcer une mise à jour de la clé
        If Not oItemCourant.Group Is Nothing Then
            If oItemCourant.Group.Items.Count = 1 Then
                Me.ListViewFichiers.Groups.Remove(oItemCourant.Group)
                oItemCourant.Group = Nothing
            End If
        End If
        Me.oItemCourant.Remove()
        'Si on remplace un document existant du même nom, on doit le retirer de la liste aussi.
        If Me.ListViewFichiers.Items.ContainsKey(CheminFichier) Then Me.ListViewFichiers.Items.RemoveByKey(CheminFichier)
        'Maintenant on peut l'ajouter
        Me.oItemCourant = Me.ListViewFichiers.Items.Add(Me.DocumentCourant.Chemin, Me.DocumentCourant.Titre, Me.DocumentCourant.GetIconeName())
        Me.oItemCourant.Text = oDocument.Titre
        Me.oItemCourant.Tag = Me.DocumentCourant
        Me.oItemCourant.SubItems.Add("")
        Dim sDossier As String = System.IO.Path.GetDirectoryName(DocumentCourant.Chemin)
        Dim oGroupe As ListViewGroup = ListViewFichiers.Groups(sDossier)
        If oGroupe Is Nothing Then oGroupe = ListViewFichiers.Groups.Add(sDossier, sDossier)
        oItemCourant.Group = oGroupe
        Me.oItemCourant.EnsureVisible()
        oDocument.oItem = Me.oItemCourant
        RechercherMarqeursDocCourant()
        Call Me.AjouteRecent(oDocument.Chemin)
        AjouterHistoriqueMacro("scpEdit.EnregistrerFichierSous(" & Chr(34) & CheminFichier & Chr(34) & ")")
    End Sub

    Public Sub EnregistrerTous()
        'Enregistrer tous les documents ouverts qui sont modifiés
        Me.ToolStripProgressBar1.Minimum = 1
        Me.ToolStripProgressBar1.Maximum = Me.ListViewFichiers.Items.Count + 1
        Me.ToolStripProgressBar1.Value = 1
        Me.ToolStripProgressBar1.Visible = True
        AjouterHistoriqueMacro("'Enregistrer tous les documents")
        For Each oItem As ListViewItem In Me.ListViewFichiers.Items
            Dim oDoc As ClassDocument = oItem.Tag
            'On utilise la procédure Enregistrer pour obtenir un nouveau nom (enregistrer sous) au besoin.
            'If oDoc.Modifie Then Enregistrer(oDoc)
            Enregistrer(oDoc)
            Me.ToolStripProgressBar1.Value += 1
            My.Application.DoEvents()
        Next
        Me.ToolStripProgressBar1.Visible = False

    End Sub

    Private Sub Ouvrir()
        'Ouvrir un document ou plusieurs documents...
        Me.OpenFileDialog1.Filter = "Tous|*.*|Texte|*.txt|Journaux|*.log|XML|*.xml"
        Me.OpenFileDialog1.DefaultExt = "Tous"
        Me.OpenFileDialog1.Title = "Fichier à modifier..."
        Me.OpenFileDialog1.Multiselect = True
        'Réutilisation du dernier dossier...
        If My.Settings.DernierDossier <> "" Then Me.OpenFileDialog1.InitialDirectory = My.Settings.DernierDossier
        'On ne veut pas le nom par défaut...
        Me.OpenFileDialog1.FileName = ""
        If Me.OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            'On des fichiers à ouvrir
            Me.RichTextBox1.Visible = False
            Me.Cursor = Cursors.WaitCursor
            Me.ToolStripProgressBar1.Minimum = 1
            Me.ToolStripProgressBar1.Maximum = Me.OpenFileDialog1.FileNames.Count + 1
            Me.ToolStripProgressBar1.Value = 1
            Me.ToolStripProgressBar1.Visible = True
            For Each sFileName As String In Me.OpenFileDialog1.FileNames()
                'On ouvre seulement les "nouveaux" fichiers...
                If Not Me.ListViewFichiers.Items.ContainsKey(sFileName) Then
                    OuvrirFichier(sFileName)
                End If
            Next
            Me.ToolStripProgressBar1.Visible = False
            If Not Me.DocumentCourant Is Nothing Then
                Me.RichTextBox1.Visible = True
                Call Me.AfficherProprietes()
            End If
            Me.Cursor = Cursors.Default
            Call AfficherStatistiquesGlobales()
            Me.TabControl1.SelectedTab = Me.TabPageEdition
        End If
    End Sub

    Public Function GetFIleName(ByVal Filtres As String) As String
        'Ouvrir un document ou plusieurs documents...
        Me.OpenFileDialog1.Filter = "Tous|*.*|Texte|*.txt|Journaux|*.log|XML|*.xml"
        If Filtres <> "" Then Me.OpenFileDialog1.Filter = Filtres
        Me.OpenFileDialog1.Title = "Fichier à ouvrir"
        Me.OpenFileDialog1.Multiselect = False
        'Réutilisation du dernier dossier...
        If My.Settings.DernierDossier <> "" Then Me.OpenFileDialog1.InitialDirectory = My.Settings.DernierDossier
        'On ne veut pas le nom par défaut...
        Me.OpenFileDialog1.FileName = ""
        If Me.OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Return Me.OpenFileDialog1.FileName
        Else
            Return ""
        End If
    End Function

    Public Sub OuvrirFichier(ByVal sFileName As String)
        'Ouvrir et afficher le fichier spécifié
        sFileName = Commun.ConvertToAdminPath(My.Computer.Name, sFileName).ToLower
        If Not Me.ListViewFichiers.Items.ContainsKey(sFileName) Then
            'Ok c'est un nouveau fichier, on crée un nouveau document
            Dim sDossier As String = System.IO.Path.GetDirectoryName(sFileName)
            My.Settings.DernierDossier = sDossier
            Me.DocumentCourant = New ClassDocument(sFileName, True)
            Me.RichTextBox1.Text = Me.DocumentCourant.Contenu
            Me.TabControl1.Visible = True
            'On l'ajoute dans la liste
            Me.oItemCourant = Me.ListViewFichiers.Items.Add(sFileName, Me.DocumentCourant.Titre, Me.DocumentCourant.GetIconeName())
            Me.oItemCourant.Selected = True
            Me.oItemCourant.SubItems.Add("")
            'On défini un groupe pour le dossier
            Dim oGroupe As ListViewGroup = ListViewFichiers.Groups(sDossier)
            If oGroupe Is Nothing Then oGroupe = ListViewFichiers.Groups.Add(sDossier, sDossier)
            oItemCourant.Group = oGroupe
            Me.oItemCourant.EnsureVisible()
            'On créé les liens
            Me.oItemCourant.Tag = Me.DocumentCourant
            Me.DocumentCourant.oItem = Me.oItemCourant
            'On actualise l'affichage
            If Me.ToolStripProgressBar1.Visible Then Me.ToolStripProgressBar1.Value += 1
            Me.RechercherMarqeursDocCourant()
            Me.DocumentCourant.ContenuRTF = Me.RichTextBox1.Rtf
            Me.DocumentCourant.ContenuMarque = Me.RichTextBoxMarque.Rtf
            My.Application.DoEvents()
            Me.EnregistrerToolStripMenuItem.Text = "Enregistrer " & Chr(34) & DocumentCourant.Titre & Chr(34)
            Call Me.UpdateCompteurs()
            Call Me.UpdateTitreFen()
            Me.RichTextBox1.SelectionStart = 0
            Me.RichTextBox1.SelectionLength = 0
            'On l'ajoute dans les fichiers récents
            Call Me.AjouteRecent(sFileName)
            'On inscrit l'historique
            AjouterHistoriqueMacro("scpEdit.OuvrirFichier (" & Chr(34) & sFileName & Chr(34) & ")")
        End If
    End Sub

    Public Sub OuvrirFichierSansActiver(ByVal sFileName As String)
        'Ouvrir sans afficher le fichier spécifié
        sFileName = Commun.ConvertToAdminPath(My.Computer.Name, sFileName).ToLower
        If Not Me.ListViewFichiers.Items.ContainsKey(sFileName) Then
            'Ok c'est un nouveau fichier, on crée un nouveau document
            Dim oNewDoc As New ClassDocument(sFileName, True)
            Dim sDossier As String = System.IO.Path.GetDirectoryName(sFileName)
            My.Settings.DernierDossier = sDossier
            'Me.RichTextBox1.Text = oNewDoc.Contenu
            Me.TabControl1.Visible = True
            'On l'ajoute dans la liste
            Me.oItemCourant = Me.ListViewFichiers.Items.Add(sFileName, oNewDoc.Titre, oNewDoc.GetIconeName())
            'Me.oItemCourant.Selected = True
            Me.oItemCourant.SubItems.Add("")
            'On défini un groupe pour le dossier
            Dim oGroupe As ListViewGroup = ListViewFichiers.Groups(sDossier)
            If oGroupe Is Nothing Then oGroupe = ListViewFichiers.Groups.Add(sDossier, sDossier)
            oItemCourant.Group = oGroupe
            Me.oItemCourant.EnsureVisible()
            'On créé les liens
            Me.oItemCourant.Tag = oNewDoc
            oNewDoc.oItem = Me.oItemCourant
            'On actualise l'affichage
            If Me.ToolStripProgressBar1.Visible Then Me.ToolStripProgressBar1.Value += 1
            'Me.RechercherCourant()
            'Me.DocumentCourant.ContenuRTF = Me.RichTextBox1.Rtf
            My.Application.DoEvents()
            'Me.EnregistrerToolStripMenuItem.Text = "Enregistrer " & Chr(34) & DocumentCourant.Titre & Chr(34)
            'Call Me.UpdateCompteurs()
            'Call Me.UpdateTitreFen()
            'Me.RichTextBox1.SelectionStart = 0
            'Me.RichTextBox1.SelectionLength = 0
            'On l'ajoute dans les fichiers récents
            Call Me.AjouteRecent(sFileName)
        End If
    End Sub
    Private Sub Chercher()
        Dim sChemin As String = My.Computer.FileSystem.SpecialDirectories.CurrentUserApplicationData & "\postes.txt"
        If My.Settings.CibleRecheche = "Local" Then
            FormChercher.RadioButtonLocal.Checked = True
        Else
            FormChercher.RadioButtonDistants.Checked = True
        End If
        FormChercher.TextBoxDossiers.Text = My.Settings.DossierRecherche
        FormChercher.TextBoxMasque.Text = My.Settings.MasqueDOS
        FormChercher.CheckBoxRecursion.Checked = (My.Settings.Recursion = Boolean.TrueString)
        FormChercher.ImporterPostes(sChemin)
        Select Case FormChercher.ShowDialog()
            Case Windows.Forms.DialogResult.OK
                'A SEPARER EN SUB DISTINCTS
                'On des fichiers et on les ouvre
                Me.ToolStripProgressBar1.Minimum = 1
                Me.ToolStripProgressBar1.Maximum = FormChercher.ListView1.CheckedItems.Count + 1
                Me.ToolStripProgressBar1.Value = 1
                Me.ToolStripProgressBar1.Visible = True
                For Each oItem As ListViewItem In FormChercher.ListView1.CheckedItems
                    Dim oDoc As ClassDocument = oItem.Tag
                    AjouteDocument(oDoc)
                Next
                Me.ToolStripProgressBar1.Visible = False
            Case Windows.Forms.DialogResult.Yes
                'A SEPARER EN SUB DISTINCTS
                'On a des fichiers, on les copie localement et on les ouvre
                Me.FolderBrowserDialog1.Description = "Copier les fichiers trouvés vers l'emplacement suivant:"
                Me.FolderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer
                If Me.FolderBrowserDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                    Me.ToolStripProgressBar1.Minimum = 1
                    Me.ToolStripProgressBar1.Maximum = FormChercher.ListView1.CheckedItems.Count + 1
                    Me.ToolStripProgressBar1.Value = 1
                    Me.ToolStripProgressBar1.Visible = True
                    For Each oItem As ListViewItem In FormChercher.ListView1.CheckedItems
                        Dim oDoc As ClassDocument = oItem.Tag
                        Dim sComputer As String = oItem.SubItems(1).Text
                        Dim sNouveau As String = Me.FolderBrowserDialog1.SelectedPath & "\" & sComputer & "_" & System.IO.Path.GetFileName(oDoc.Chemin)
                        If Not oDoc.Loaded Then oDoc.ChargerContenu()
                        oDoc.EnregistrerSous(sNouveau)
                        AjouteDocument(oDoc)
                    Next
                    Me.ToolStripProgressBar1.Visible = False
                Else
                    MsgBox("Copie des fichiers trouvés annulée!", MsgBoxStyle.Exclamation)
                End If
        End Select
        My.Settings.MasqueDOS = FormChercher.TextBoxMasque.Text
        My.Settings.Recursion = FormChercher.CheckBoxRecursion.Checked.ToString
        FormChercher.ExporterPostes(sChemin)
        My.Settings.DossierRecherche = FormChercher.TextBoxDossiers.Text
        If FormChercher.RadioButtonLocal.Checked Then
            My.Settings.CibleRecheche = "Local"
        Else
            My.Settings.CibleRecheche = "Distants"
        End If

    End Sub

    Public Sub AjouteDocument(ByRef oDoc As ClassDocument)
        If Not Me.ListViewFichiers.Items.ContainsKey(oDoc.Chemin) Then
            Me.DocumentCourant = oDoc
            My.Settings.DernierDossier = My.Computer.FileSystem.GetParentPath(oDoc.Chemin)
            Me.RichTextBox1.Text = Me.DocumentCourant.Contenu
            Me.TabControl1.Visible = True
            'On l'ajoute dans la liste
            Me.oItemCourant = Me.ListViewFichiers.Items.Add(Me.DocumentCourant.Chemin, Me.DocumentCourant.Titre, Me.DocumentCourant.GetIconeName())
            'On défini un groupe pour le dossier
            Dim sDossier As String = System.IO.Path.GetDirectoryName(Me.DocumentCourant.Chemin)
            Dim oGroupe As ListViewGroup = ListViewFichiers.Groups(sDossier)
            If oGroupe Is Nothing Then oGroupe = ListViewFichiers.Groups.Add(sDossier, sDossier)
            oItemCourant.Group = oGroupe
            Me.oItemCourant.EnsureVisible()
            Me.oItemCourant.Tag = Me.DocumentCourant
            Me.DocumentCourant.oItem = Me.oItemCourant
            Me.oItemCourant.Selected = True
            Me.oItemCourant.SubItems.Add("")
            'Me.ToolStripProgressBar1.Value += 1
            Me.RechercherMarqeursDocCourant()
            Me.DocumentCourant.ContenuRTF = Me.RichTextBox1.Rtf
            My.Application.DoEvents()
            Call Me.UpdateCompteurs()
            Me.RichTextBox1.Visible = True
        End If
    End Sub

    Public Sub Nouveau()
        Dim oNewDocument As New ClassDocument("", False)
        Dim oNewItem As ListViewItem = Me.ListViewFichiers.Items.Add(oNewDocument.Titre, oNewDocument.Titre, oNewDocument.GetIconeName())
        oNewItem.SubItems.Add("")
        oNewItem.Tag = oNewDocument
        oNewDocument.oItem = oNewItem
        oNewItem.Selected = True
        Dim oGroupe As ListViewGroup = ListViewFichiers.Groups("*Nouveau")
        If oGroupe Is Nothing Then oGroupe = ListViewFichiers.Groups.Add("*Nouveau", "*Nouveau")
        oNewItem.Group = oGroupe
        Me.RichTextBox1.Visible = True
        AfficheCourant(oNewItem)
        Me.TabControl1.SelectedTab = Me.TabPageEdition
        AjouterHistoriqueMacro("scpEdit.Nouveau()")
    End Sub

    Public Sub SupprimerCourantAuto()
        'Version non interactive
        Dim oDocument As ClassDocument = Me.DocumentCourant
        If oDocument IsNot Nothing Then
            If oDocument.Supprimer() Then
                'On ajuste les compteurs
                'IdocModif
                'On ajoute le groupe de l'item dans le listview
                If Not oDocument.oItem.Group Is Nothing Then
                    If oDocument.oItem.Group.Items.Count = 1 Then
                        Me.ListViewFichiers.Groups.Remove(oDocument.oItem.Group)
                        oDocument.oItem.Group = Nothing
                    End If
                End If
                'On retire l'item et on supprime l'objet document
                oDocument.oItem.Remove()
                Me.oItemCourant = Nothing
                Me.DocumentCourant = Nothing
                Me.RichTextBox1.Text = ""
                Me.TabControl1.Visible = False
                'On sélectionne un nouveau document par défaut
                If Me.ListViewFichiers.Items.Count > 0 Then
                    Me.ListViewFichiers.Items(0).Selected = True
                    Me.AfficheCourant(Me.ListViewFichiers.Items(0))
                Else
                    Me.EnregistrerToolStripMenuItem.Text = "Enregistrer"
                End If
                'Mettre la ligne de status à jour
                Call Me.UpdateStatus()
                Call Me.UpdateCompteurs()
                Call Me.UpdateTitreFen()
            End If
        End If
    End Sub

    Public Sub SupprimerCourant(ByRef oDocument As ClassDocument)
        'On confirme toujours
        If Me.DocumentCourant IsNot Nothing Then
            If MsgBox("Fermer et supprimer " & oDocument.Titre & "?", MsgBoxStyle.Question Or MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
                Me.SupprimerCourantAuto()
                AjouterHistoriqueMacro("scpEdit.SupprimerCourant()")
            End If
        End If
    End Sub

    Public Sub Fermer(ByRef oDocument As ClassDocument)
        If Not oDocument.oItem Is Nothing Then
            If oDocument.oItem.Selected Then oDocument.Contenu = Me.RichTextBox1.Text
        End If
        If oDocument.Modifie Then
            Select Case MsgBox("Enregistrer les changements pour " & oDocument.Titre & "?", MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Question)
                Case MsgBoxResult.Yes
                    Call Me.Enregistrer(oDocument)
                Case MsgBoxResult.Cancel
                    Exit Sub
            End Select
        End If
        'On ajuste les compteurs
        'iDocModif
        'Item
        If Not oDocument.oItem.Group Is Nothing Then
            If oDocument.oItem.Group.Items.Count = 1 Then
                Me.ListViewFichiers.Groups.Remove(oDocument.oItem.Group)
                oDocument.oItem.Group = Nothing
            End If
        End If
        oDocument.oItem.Remove()
        Me.oItemCourant = Nothing
        Me.DocumentCourant = Nothing
        Me.RichTextBox1.Text = ""
        Me.TabControl1.Visible = False
        If Me.ListViewFichiers.Items.Count > 0 Then
            Me.ListViewFichiers.Items(0).Selected = True
            Me.AfficheCourant(Me.ListViewFichiers.Items(0))
        Else
            Me.EnregistrerToolStripMenuItem.Text = "Enregistrer"
        End If
        'Mettre la ligne de status à jour
        Call Me.UpdateStatus()
        Call Me.UpdateCompteurs()
        UpdateTitreFen()
        AjouterHistoriqueMacro("scpEdit.FermerFichier()")

    End Sub

    Public Sub FermerTous()
        Me.RichTextBox1.Visible = False
        AjouterHistoriqueMacro("scpEdit.FermerTous()")
        Dim bCapture As Boolean = Commun.CaptureMacro
        Commun.CaptureMacro = False
        For Each oItem As ListViewItem In Me.ListViewFichiers.Items
            Fermer(oItem.Tag)
        Next
        Commun.CaptureMacro = bCapture
    End Sub

    Public Sub FermerTousSaufCourant()
        If DocumentCourant IsNot Nothing Then
            Dim GarderOuvert As ClassDocument = DocumentCourant
            Me.RichTextBox1.Visible = False
            For Each oItem As ListViewItem In Me.ListViewFichiers.Items
                If Not ListViewItem.Equals(oItem.Tag, GarderOuvert) Then Fermer(oItem.Tag)
            Next
            Call AfficherStatistiquesGlobales()
            Me.RichTextBox1.Visible = True
            GarderOuvert = Nothing
        End If
        AjouterHistoriqueMacro("scpEdit.FermerTousSaufCourant()")

    End Sub

    Public Sub AfficheCourant(ByVal oItem As ListViewItem)
        If Not oItem Is Nothing Then
            'Enregistre le contenu courant
            If Me.DocumentCourant Is Nothing Then
                Me.RichTextBox1.Text = ""
                Me.RichTextBoxMarque.Text = ""
                Me.TabControl1.Visible = True
            Else
                Me.DocumentCourant.Contenu = Me.RichTextBox1.Text
                Me.DocumentCourant.ContenuRTF = Me.RichTextBox1.Rtf
                Me.DocumentCourant.ContenuMarque = Me.RichTextBoxMarque.Rtf
                Me.DocumentCourant.GetSel()
            End If
            'Mettre les objets à jour
            Me.oItemCourant = oItem
            Me.DocumentCourant = oItemCourant.Tag
            'Afficher le contenu
            Me.RichTextBox1.ZoomFactor = CSng(1)
            If Me.DocumentCourant.ContenuRTF <> "" Then
                Me.RichTextBox1.Rtf = Me.DocumentCourant.ContenuRTF
                Me.RichTextBoxMarque.Rtf = Me.DocumentCourant.ContenuMarque
            Else
                Me.RichTextBox1.Text = Me.DocumentCourant.Contenu
            End If
            Me.NumericUpDownZoom.Value = Me.DocumentCourant.ZoomFactor * 100
            Me.DocumentCourant.SetSel()
            'Affiche les infos
            Me.EnregistrerToolStripMenuItem.Text = "Enregistrer " & Chr(34) & DocumentCourant.Titre & Chr(34)
            Me.UpdateStatus()
            UpdateTitreFen()
            Me.RichTextBox1.Focus()
            'Afficher les propriétés du fichier
            Me.AfficherProprietes()
        End If
    End Sub

    Public Sub AfficherProprietes()
        If Not DocumentCourant.oInfo Is Nothing Then
            Me.LabelNom.Text = Me.DocumentCourant.oInfo.Name
            Me.LabelDossier.Text = Me.DocumentCourant.oInfo.DirectoryName
            Me.LabelTaille.Text = Me.DocumentCourant.oInfo.Length.ToString("0") & " octets"
            Me.LabelModif.Text = Me.DocumentCourant.oInfo.LastWriteTime.ToString("g")
            Me.LabelCreation.Text = Me.DocumentCourant.oInfo.CreationTime.ToString("g")
            Me.LabelDernierAcces.Text = Me.DocumentCourant.oInfo.LastAccessTime.ToString("g")
            Me.LabelAttributs.Text = Me.DocumentCourant.oInfo.Attributes.ToString()
            Me.ButtonSecurite.Enabled = True
            Me.Button2.Enabled = True
            If Me.DocumentCourant.Historique.Count > 0 Then
                Me.RechergerLaDernièreVersionHistoriqueDisponibleToolStripMenuItem.Enabled = True
                Me.LabelHisto.Text = DocumentCourant.Historique.Count.ToString("0")
            Else
                Me.RechergerLaDernièreVersionHistoriqueDisponibleToolStripMenuItem.Enabled = False
                Me.LabelHisto.Text = DocumentCourant.Historique.Count.ToString("Aucune")
            End If
        Else
            Me.LabelNom.Text = "N/A"
            Me.LabelDossier.Text = "N/A"
            Me.LabelTaille.Text = "N/A"
            Me.LabelModif.Text = "N/A"
            Me.LabelCreation.Text = "N/A"
            Me.LabelDernierAcces.Text = "N/A"
            Me.LabelAttributs.Text = "N/A"
            Me.ButtonSecurite.Enabled = False
            Me.Button2.Enabled = False
        End If
        Me.LabelTexteLignes.Text = Me.RichTextBox1.Lines.Count.ToString("0")
        Me.LabelTexteLongueur.Text = Me.RichTextBox1.TextLength.ToString("0")

    End Sub

    Public Sub UpdateStatus()
        Me.ToolStripStatusDocTrouve.Text = "Docs " & Me.ListViewFichiers.Items.Count.ToString("0")
    End Sub

    Public Sub FermerSansMarques()
        Me.RichTextBox1.Visible = False
        For Each oItem As ListViewItem In Me.ListViewFichiers.Items
            Dim oDoc As ClassDocument = oItem.Tag
            If oDoc.iTrouve = 0 Then Me.Fermer(oDoc)
        Next
        If Not Me.DocumentCourant Is Nothing Then
            Me.RichTextBox1.Visible = True
            Call AfficherStatistiquesGlobales()
        End If
        AjouterHistoriqueMacro("scpEdit.FermerSansMarques()")
    End Sub

    Public Sub RechargerCourantAuto()
        'Recharger le document courant, sans confirmation
        Dim bRecharger As Boolean = True
        Me.RichTextBox1.Visible = False
        Me.DocumentCourant.ChargerContenu()
        Me.RichTextBox1.Text = Me.DocumentCourant.Contenu
        Me.RechercherMarqeursDocCourant()
        Me.RichTextBox1.Visible = True
    End Sub

    Public Sub RechargerCourant()
        'Recharger le document courant
        Dim bRecharger As Boolean = True
        If DocumentCourant.Modifie Then bRecharger = (MsgBox("Recharger le fichier " & DocumentCourant.Titre & " original et perdre vos modifications ?", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok)
        If bRecharger Then
            RechargerCourantAuto()
            AjouterHistoriqueMacro("scpEdit.RechargerCourant()")
        End If
    End Sub

    Public Sub AjouteRecent(ByVal sFileName As String)
        If My.Settings.Recents.Contains(sFileName.ToLower) Then My.Settings.Recents.Remove(sFileName.ToLower)
        If My.Settings.Recents.Count = 10 Then My.Settings.Recents.RemoveAt(9)
        My.Settings.Recents.Insert(0, sFileName.ToLower)
        UpdateRecents()
    End Sub

    Public Sub UpdateRecents()
        Me.RécentsToolStripMenuItem.DropDownItems.Clear()
        For Each sFichier In My.Settings.Recents
            If My.Computer.FileSystem.FileExists(sFichier) Then Me.RécentsToolStripMenuItem.DropDownItems.Add(sFichier)
        Next
    End Sub

#End Region

#Region "Edition"
    Private Sub QuickTransform(ByRef Sender As System.Object, ByVal Op As ClassTextOp.EnumTextOperation)
        'Test
        If Me.DocumentCourant Is Nothing Then Exit Sub
        Dim oTextOP As New ClassTextOp
        Dim Visible As Boolean = Me.RichTextBox1.Visible
        oTextOP.Operation = Op
        If oTextOP.EditParams() Then
            'Cas particulier des remplacements text, regex et lookup
            If (oTextOP.Operation = ClassTextOp.EnumTextOperation.RemplacerTexte Or oTextOP.Operation = ClassTextOp.EnumTextOperation.RemplacerRegEx Or oTextOP.Operation = ClassTextOp.EnumTextOperation.Lookup) And (Me.RichTextBox1.SelectionLength > 0) Then
                If MsgBox("Appliquer le remplacement au texte entier ?", MsgBoxStyle.Question Or MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then Me.RichTextBox1.SelectionLength = 0
            End If
            Me.RichTextBox1.Visible = False
            If Me.RichTextBox1.SelectionLength > 0 Then
                'Appliquer le changement à la sélection
                Me.RichTextBox1.SelectedText = oTextOP.Transformer(Me.RichTextBox1.SelectedText)
                AjouterHistoriqueMacro("scpEdit.TransformerSelection " & oTextOP.ToMacro)
            Else
                If RestreindreAuTexteMarqueToolStripMenuItem.Checked And (Me.ListViewMarqueurs.CheckedItems.Count > 0) Then
                    'Applique le changement au texte marqué
                    Call TransformerRecCourant(oTextOP)
                    AjouterHistoriqueMacro("scpEdit.TransformerMarqueurs " & oTextOP.ToMacro)
                Else
                    'Appliquer le changement à tout le texte
                    Me.RichTextBox1.Text = oTextOP.Transformer(Me.RichTextBox1.Text)
                    AjouterHistoriqueMacro("scpEdit.Transformer " & oTextOP.ToMacro)
                End If
            End If
            Call Me.RechercherMarqeursDocCourant()
            Me.RichTextBox1.Visible = Visible
            oTextOP = Nothing
            Me.ToolStripSplitButton1.Image = Sender.Image
            Me.ToolStripSplitButton1.DefaultItem = Sender
            Me.ToolStripSplitButton1.Text = Sender.OwnerItem.Text & "\" & Sender.Text
        End If
    End Sub

    Private Sub SelectLigne()
        Me.RichTextBox1.SelectionStart = Me.RichTextBox1.GetFirstCharIndexOfCurrentLine()
        Me.RichTextBox1.SelectionLength = Me.RichTextBox1.Lines(Me.RichTextBox1.GetLineFromCharIndex(Me.RichTextBox1.SelectionStart)).Length
    End Sub

    Public Sub DeleteLigne()


        If Me.RichTextBox1.TextLength > 0 Then
            SelectLigne()
            'On inclus le \n
            If Me.RichTextBox1.SelectionStart + Me.RichTextBox1.SelectionLength < Me.RichTextBox1.TextLength Then Me.RichTextBox1.SelectionLength += 1
            Me.RichTextBox1.SelectedText = ""
        End If

        AjouterHistoriqueMacro("scpEdit.SupprimeLigne()")
    End Sub

    Public Sub DeleteColonne()


        If Me.RichTextBox1.TextLength > 0 Then
            If Me.RichTextBox1.SelectionLength = 0 Then
                'Methode 1 - colonne délimitée par des espaces
                Dim NoColonne As Integer = GetColonne()
                Dim NoLigne As Integer = GetLigne()
                Dim iIndex As Integer = NoLigne
                While SelectColonneDelimitee(iIndex, NoColonne)
                    Me.RichTextBox1.SelectedText = ""
                    iIndex -= 1
                End While
                iIndex = NoLigne + 1
                While SelectColonneDelimitee(iIndex, NoColonne)
                    Me.RichTextBox1.SelectedText = ""
                    iIndex += 1
                End While
            Else
                'Méthode 2 - par la largeur sélectionnée
                Dim NoColonne As Integer = GetColonne()
                Dim LargeurColonne As Integer = Me.RichTextBox1.SelectionLength
                Dim NoLigne As Integer = GetLigne()
                Dim iIndex As Integer = NoLigne
                While SelectColonnePosition(iIndex, NoColonne, LargeurColonne)
                    Me.RichTextBox1.SelectedText = ""
                    iIndex -= 1
                End While
                iIndex = NoLigne + 1
                While SelectColonnePosition(iIndex, NoColonne, LargeurColonne)
                    Me.RichTextBox1.SelectedText = ""
                    iIndex += 1
                End While
            End If
        End If

        AjouterHistoriqueMacro("scpEdit.SupprimeColonne")
    End Sub

    Private Function GetColonne()
        Dim First As Integer = Me.RichTextBox1.GetFirstCharIndexOfCurrentLine()
        Return Me.RichTextBox1.SelectionStart - First
    End Function

    Private Function GetLigne()
        Return Me.RichTextBox1.GetLineFromCharIndex(Me.RichTextBox1.SelectionStart)
    End Function

    Private Function SelectColonneDelimitee(ByVal Ligne As Integer, ByVal Colonne As Integer) As Boolean
        SelectColonneDelimitee = False
        If (Ligne >= 0) And (Ligne < Me.RichTextBox1.Lines.Count) Then
            Dim Longueur As Integer = Me.RichTextBox1.Lines(Ligne).Length
            If Colonne < Longueur Then
                Dim iPremier As Integer = Me.RichTextBox1.GetFirstCharIndexFromLine(Ligne)
                Dim iDernier As Integer = iPremier + Longueur
                Dim iDebut As Integer = iPremier + Colonne
                Dim iFin As Integer = iDebut
                While (iDebut > iPremier) And (Me.RichTextBox1.Text(iDebut) <> " ")
                    iDebut -= 1
                End While
                While (iFin < iDernier) And (Me.RichTextBox1.Text(iFin) <> " ")
                    iFin += 1
                End While
                Me.RichTextBox1.SelectionStart = iDebut
                Me.RichTextBox1.SelectionLength = iFin - iDebut
                SelectColonneDelimitee = (iDebut <> iFin)
            End If
        End If
    End Function

    Private Function SelectColonnePosition(ByVal Ligne As Integer, ByVal Colonne As Integer, ByVal LongueurCol As Integer) As Boolean
        SelectColonnePosition = False
        If (Ligne >= 0) And (Ligne < Me.RichTextBox1.Lines.Count) Then
            Dim Longueur As Integer = Me.RichTextBox1.Lines(Ligne).Length
            If Colonne + LongueurCol < Longueur Then
                Dim iPremier As Integer = Me.RichTextBox1.GetFirstCharIndexFromLine(Ligne)
                Me.RichTextBox1.SelectionStart = iPremier + Colonne
                Me.RichTextBox1.SelectionLength = LongueurCol
                SelectColonnePosition = True
            End If
        End If
    End Function

    Public Sub CopierAjouter()


        Dim Contenu As String = Me.RichTextBox1.SelectedText
        If Clipboard.ContainsText Then Contenu = Clipboard.GetText(TextDataFormat.Text) & Contenu
        Clipboard.SetText(Contenu, TextDataFormat.Text)
        Me.RichTextBox1.SelectionLength = 0

        AjouterHistoriqueMacro("scpEdit.CopierAjouter()")
    End Sub

    Public Sub Dupliquer()


        If Me.RichTextBox1.SelectionLength = 0 Then
            'Dupliquer la ligne courante
            Dim Pos1 As Integer = RichTextBox1.GetFirstCharIndexOfCurrentLine()
            Dim NoLigne As Integer = RichTextBox1.GetLineFromCharIndex(Pos1)
            Dim Contenu As String = RichTextBox1.Lines(NoLigne)
            If NoLigne = (Me.RichTextBox1.Lines.Count - 1) Then
                'On ajoute à la fin
                Me.RichTextBox1.Text &= vbLf & Contenu
            Else
                'On insère une nouvelle ligne
                Me.RichTextBox1.SelectionStart = Me.RichTextBox1.GetFirstCharIndexFromLine(NoLigne + 1)
                Me.RichTextBox1.SelectedText = Contenu & vbLf
            End If
            Me.RichTextBox1.SelectionStart = Pos1
        Else
            'Dupliquer la sélection
            Dim Pos As Integer = Me.RichTextBox1.SelectionStart
            Dim Len As Integer = Me.RichTextBox1.SelectionLength
            Me.RichTextBox1.SelectedText &= Me.RichTextBox1.SelectedText
            Me.RichTextBox1.SelectionStart = Pos
            Me.RichTextBox1.SelectionLength = Len
        End If

        AjouterHistoriqueMacro("scpEdit.Dupliquer()")
    End Sub

    Private Sub InsertTab()
        'Le tabulateur doit s'aligner sur la ligne précédente.
        Dim NoLigne As Integer = Me.RichTextBox1.GetLineFromCharIndex(Me.RichTextBox1.SelectionStart)
        Dim Pos1 As Integer = Me.RichTextBox1.GetFirstCharIndexOfCurrentLine
        Dim NoColonne As Integer = Me.RichTextBox1.SelectionStart - Pos1
        Dim nbcar As Integer = 0
        'On vérifie si on peut s'aligner sur la ligne précédente
        If NoLigne > 0 Then
            Dim Contenu As String = Me.RichTextBox1.Lines(NoLigne - 1)
            For Each oMatch As Match In System.Text.RegularExpressions.Regex.Matches(Contenu, "\s+", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
                If (oMatch.Index + oMatch.Length) > NoColonne Then
                    nbcar = (oMatch.Index + oMatch.Length) - NoColonne
                    Exit For
                End If
            Next
        End If
        If nbcar = 0 Then nbcar = 4
        If Me.RichTextBox1.SelectionLength > 0 Then
            Call Me.IndentText(nbcar)
        Else
            Me.RichTextBox1.SelectedText = Space(nbcar) & Me.RichTextBox1.SelectedText
        End If
    End Sub

    Public Sub Couper()


        If Me.RichTextBox1.SelectedText <> "" Then
            Me.RichTextBox1.Cut()
        End If

        AjouterHistoriqueMacro("scpEdit.Couper()")
    End Sub

    Public Sub Copier()
        My.Application.DoEvents()
        If Me.TabControl1.SelectedTab.Name = "TabPageMarque" Then
            If Me.RichTextBoxMarque.SelectedText <> "" Then
                Clipboard.Clear()
                Clipboard.SetText(Me.RichTextBoxMarque.SelectedText.Replace(vbLf, vbCrLf), TextDataFormat.Text)
            End If
        Else
            If Me.RichTextBox1.SelectedText <> "" Then
                Clipboard.Clear()
                Clipboard.SetText(Me.RichTextBox1.SelectedText.Replace(vbLf, vbCrLf), TextDataFormat.Text)
                AjouterHistoriqueMacro("scpEdit.Selection " & Me.RichTextBox1.SelectionStart & "," & Me.RichTextBox1.SelectionLength)
                AjouterHistoriqueMacro("scpEdit.Copier()")
            End If
        End If
    End Sub

    Private Sub CopierRTF()
        My.Application.DoEvents()
        If Me.RichTextBox1.SelectedRtf <> "" Then
            Clipboard.Clear()
            Clipboard.SetText(Me.RichTextBox1.SelectedRtf, TextDataFormat.Rtf)
        End If
        AjouterHistoriqueMacro("scpEdit.Selection " & Me.RichTextBox1.SelectionStart & "," & Me.RichTextBox1.SelectionLength)
        AjouterHistoriqueMacro("scpEdit.CopierRTF()")
    End Sub

    Public Sub Coller()
        If Not Me.DocumentCourant Is Nothing Then
            Dim sTexte As String = Clipboard.GetText()
            If InStr(sTexte, vbTab) Then
                If MsgBox("Convertir les tabulateurs en espace ?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question) Then sTexte = Replace(sTexte, vbTab, " ")
            End If
            Me.RichTextBox1.SelectedText = sTexte
        End If
        AjouterHistoriqueMacro("scpEdit.Coller()")
    End Sub

    Public Sub CollerColonne()
        If Not Me.DocumentCourant Is Nothing Then
            Dim sTexte As String = Clipboard.GetText()
            sTexte = sTexte.Replace(vbCrLf, vbLf)
            If InStr(sTexte, vbTab) Then
                If MsgBox("Convertir les tabulateurs en espace ?", MsgBoxStyle.YesNo Or MsgBoxStyle.Question) Then sTexte = Replace(sTexte, vbTab, " ")
            End If
            Dim iColonne As Integer = GetColonne()
            Dim iLigne As Integer = GetLigne()
            Me.RichTextBox1.SelectionLength = 0
            For Each sLigne As String In sTexte.Split(vbLf)
                Me.RichTextBox1.SelectedText = sLigne
                'On descend d'une ligne
                iLigne += 1
                If iLigne >= Me.RichTextBox1.Lines.Length Then Me.RichTextBox1.AppendText(vbLf)
                Me.RichTextBox1.SelectionStart = Me.RichTextBox1.GetFirstCharIndexFromLine(iLigne)
                'On allonge la ligne au besoin
                If Me.RichTextBox1.Lines(iLigne).Length < iColonne Then
                    Me.RichTextBox1.SelectionStart += Me.RichTextBox1.Lines(iLigne).Length
                    Me.RichTextBox1.SelectedText = Space(iColonne - Me.RichTextBox1.Lines(iLigne).Length)
                End If
                Me.RichTextBox1.SelectionStart = Me.RichTextBox1.GetFirstCharIndexFromLine(iLigne) + iColonne
            Next
        End If

        AjouterHistoriqueMacro("scpEdit.CollerColonne()")
    End Sub

    Public Sub Undo()
        If (Me.RichTextBox1.UndoActionName <> "") And (Me.RichTextBox1.UndoActionName <> "Unknown") Then
            Me.RichTextBox1.Undo()
        Else
            If Not Me.DocumentCourant Is Nothing Then
                Me.DocumentCourant.Undo()
                Me.RichTextBox1.Rtf = Me.DocumentCourant.ContenuRTF
            End If
        End If
        AjouterHistoriqueMacro("scpEdit.Undo()")
    End Sub

    Public Sub UndoAll()
        Do While (Me.RichTextBox1.UndoActionName <> "") And (Me.RichTextBox1.UndoActionName <> "Unknown")
            Me.RichTextBox1.Undo()
        Loop
        AjouterHistoriqueMacro("scpEdit.UndoAll()")
    End Sub

    Public Sub Redo()
        Me.RichTextBox1.Redo()
        AjouterHistoriqueMacro("scpEdit.Redo()")
    End Sub

    Private Sub Calculer(ByVal Remplacer As Boolean)
        Dim Formule As String
        Dim Result As String
        Dim iPos As Integer = Me.RichTextBox1.SelectionStart
        If Me.RichTextBox1.SelectionLength = 0 Then
            Me.RichTextBox1.SelectionStart = Me.RichTextBox1.GetFirstCharIndexOfCurrentLine()
            Me.RichTextBox1.SelectionLength = iPos - Me.RichTextBox1.SelectionStart
        End If
        Formule = Me.RichTextBox1.SelectedText.Trim()
        'Formule = Regex.Replace(Formule, "\s\s+", "+")
        'If Formule.Contains("=") Then Formule = ""
        If TestRegex(Formule, "[\d\s].*") Then Formule = Regex.Replace(Formule, "\s+", "+")
        If Formule <> "" Then
            Try
                Dim oExpressionTree As New ExpressionTree(Formule)
                Result = oExpressionTree.Evaluate()
            Catch ex As Exception
                'On n'a pas de formule valide, donc en tente une somme
                Result = CalculerSomme()
            End Try
        Else
            Me.RichTextBox1.SelectionLength = 0
            Me.RichTextBox1.SelectionStart = iPos
            Result = CalculerSomme()
        End If
        If Result <> "" Then
            If Remplacer Then
                Me.RichTextBox1.SelectedText = Result
            Else
                Me.RichTextBox1.SelectedText &= "=" & Result
            End If
        End If
    End Sub

    Private Function CalculerSomme() As String
        Dim iPos As Integer = Me.RichTextBox1.SelectionStart
        Dim iLen As Integer = Me.RichTextBox1.SelectionLength
        Dim Formule As String = GetFormule(Me.RichTextBox1.SelectedText)
        If Formule = "" Then
            'On essai d'additionner la colonne courante
            Me.RichTextBox1.SelectionStart = iPos
            Formule = GetFormule(GetTexteColonne())
        End If
        FormCalc.TextBox1.Text = Formule
        FormCalc.Actualiser()
        Me.RichTextBox1.SelectionStart = iPos
        Me.RichTextBox1.SelectionLength = iLen
        If FormCalc.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Return FormCalc.LabelResult.Text
        Else
            Return ""
        End If
    End Function

    Private Function GetTexteColonne() As String
        Dim Result As String = ""
        Dim NoColonne As Integer = GetColonne()
        Dim NoLigne As Integer = GetLigne()
        If NoLigne > 0 Then NoLigne -= 1
        Dim iIndex As Integer = NoLigne
        While SelectColonneDelimitee(iIndex, NoColonne)
            Result &= Me.RichTextBox1.SelectedText() & vbLf
            iIndex -= 1
        End While
        iIndex = NoLigne + 1
        While SelectColonneDelimitee(iIndex, NoColonne)
            Result &= Me.RichTextBox1.SelectedText & vbLf
            iIndex += 1
        End While
        Return Result
    End Function

    Private Function GetFormule(ByVal Chaine As String)
        'On regarde la sélection courante
        Dim Formule As String = ""
        If Not Chaine.Contains("=") Then
            For Each oMatch As Match In System.Text.RegularExpressions.Regex.Matches(Chaine, "\d+(,\d+)?")
                If Formule <> "" Then Formule &= "+"
                Formule &= oMatch.Value
            Next
        End If
        Return Formule
    End Function

    Private Sub RemplacerTransformer()
        If Me.ListViewFichiers.Items.Count > 0 Then
            'On travaille avec une transformation vierge
            Dim oTextTransform = New ClassTextTransform
            oTextTransform.CopyToForm()
            'Texte sélectionné dans l'interface ?
            FormTransform.RadioButtonSelection.Enabled = (Me.RichTextBox1.SelectedText <> "")
            'On prend le document complet si la sélection est de taille nulle
            If FormTransform.RadioButtonSelection.Checked And Me.RichTextBox1.SelectionLength = 0 Then FormTransform.RadioButtonDoc.Checked = True
            'Texte d'essai
            FormTransform.RichTextBox1.Text = Me.RichTextBox1.SelectedText
            'Go...
            FormTransform.ComboBox1.Text = ""
            If FormTransform.ShowDialog() = Windows.Forms.DialogResult.OK Then
                oTextTransform.GetFromForm()
                Dim oldItem As ListViewItem = Me.oItemCourant
                Dim oldStart As Integer = Me.RichTextBox1.SelectionStart
                Dim oldLen As Integer = Me.RichTextBox1.SelectionLength
                My.Application.DoEvents()
                Me.Cursor = Cursors.WaitCursor
                If FormTransform.RadioButtonSelection.Checked Then
                    'Sélection courante
                    Me.RichTextBox1.SelectedText = oTextTransform.Transformer(Me.RichTextBox1.SelectedText)
                    Call Me.RechercherMarqeursDocCourant()
                ElseIf FormTransform.RadioButtonDoc.Checked Then
                    'Document courant
                    Me.RichTextBox1.Text = oTextTransform.Transformer(Me.RichTextBox1.Text)
                    Call Me.RechercherMarqeursDocCourant()
                ElseIf FormTransform.RadioButtonDocAll.Checked Then
                    'Tous les documents
                    For Each oItem As ListViewItem In Me.ListViewFichiers.Items
                        Me.AfficheCourant(oItem)
                        Me.RichTextBox1.Text = oTextTransform.Transformer(Me.RichTextBox1.Text)
                        Call Me.RechercherMarqeursDocCourant()
                    Next
                ElseIf FormTransform.RadioButtonRec.Checked Then
                    Call Me.TransformerRecCourant(oTextTransform)
                    Call Me.RechercherMarqeursDocCourant()
                ElseIf FormTransform.RadioButtonRecAll.Checked Then
                    'Résultats de la recherche dans tous les documents
                    For Each oItem As ListViewItem In Me.ListViewFichiers.Items
                        AfficheCourant(oItem)
                        Call Me.TransformerRecCourant(oTextTransform)
                        Call Me.RechercherMarqeursDocCourant()
                    Next
                End If
                Me.Cursor = Cursors.Default
                If oItemCourant.Name <> oldItem.Name Then AfficheCourant(oldItem)
                Me.RichTextBox1.SelectionStart = oldStart
                Me.RichTextBox1.SelectionLength = oldLen
            End If
        Else
            MsgBox("Les remplacements/tranformations ne sont disponibles que s'il y a au moins un fichier ouvert!", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub TransformerRecCourant(ByRef oTextTransform As ClassTextTransform)
        'Appliquer un groupe de transformations aux marqueurs du document courant
        Dim DeltaPos As Integer = 0
        Dim NewTexte As String
        For Each oItem As ListViewItem In Me.ListViewMarqueurs.CheckedItems
            Dim oMasque As ClassMarqueur = oItem.Tag
            Dim oRegex As New System.Text.RegularExpressions.Regex(oMasque.Masque, RegexOptions.IgnoreCase Or RegexOptions.Multiline)
            For Each oMatch As Match In oRegex.Matches(Me.RichTextBox1.Text)
                Me.RichTextBox1.SelectionStart = oMatch.Index + DeltaPos
                Me.RichTextBox1.SelectionLength = oMatch.Length
                NewTexte = oTextTransform.Transformer(Me.RichTextBox1.SelectedText)
                'On doit tenir compte des changements de longueur de texte
                DeltaPos += (NewTexte.Length - Me.RichTextBox1.SelectionLength)
                Me.RichTextBox1.SelectedText = NewTexte
            Next
        Next
        'On raffraichit la recherche
        Me.RechercherMarqeursDocCourant()
    End Sub

    Public Sub TransformerRecCourant(ByRef oTextOP As ClassTextOp)
        'Appliquer une opération de transformation aux marqueurs dans le document courant
        Dim DeltaPos As Integer = 0
        Dim NewTexte As String
        For Each oItem As ListViewItem In Me.ListViewMarqueurs.CheckedItems
            Dim oMasque As ClassMarqueur = oItem.Tag
            Dim oRegex As New System.Text.RegularExpressions.Regex(oMasque.Masque, RegexOptions.IgnoreCase Or RegexOptions.Multiline)
            For Each oMatch As Match In oRegex.Matches(Me.RichTextBox1.Text)
                Me.RichTextBox1.SelectionStart = oMatch.Index + DeltaPos
                Me.RichTextBox1.SelectionLength = oMatch.Length
                NewTexte = oTextOP.Transformer(Me.RichTextBox1.SelectedText)
                'On doit tenir compte des changements de longueur du texte.
                DeltaPos += (NewTexte.Length - Me.RichTextBox1.SelectionLength)
                Me.RichTextBox1.SelectedText = NewTexte
            Next
        Next
        'On raffraichit la recherche
        Me.RechercherMarqeursDocCourant()
    End Sub

    Private Sub AjusterMenus()
        Me.AnnulerToolStripMenuItem.Enabled = Me.RichTextBox1.CanUndo
        Me.AnnulerToolStripMenuItem.Text = "Annuler " & Me.RichTextBox1.UndoActionName
        Me.RefaireToolStripMenuItem.Enabled = Me.RichTextBox1.CanRedo
        Me.RefaireToolStripMenuItem.Text = "Refaire " & Me.RichTextBox1.RedoActionName
    End Sub

    Public Sub AtteindreLigneAuto(ByVal NoLigne As Integer)
        If NoLigne < 0 Then NoLigne = 0
        Me.RichTextBox1.SelectionStart = Me.RichTextBox1.GetFirstCharIndexFromLine(noLigne)
        AjouterHistoriqueMacro("scpEdit.AtteindreLigne(" & noLigne + 1 & ")")
    End Sub

    Private Sub AtteindreLigne()
        If Not DocumentCourant Is Nothing Then
            FormAtteindre.NumericUpDownLigne.Minimum = 1
            FormAtteindre.TrackBar1.Minimum = 1
            FormAtteindre.NumericUpDownLigne.Maximum = Me.RichTextBox1.Lines.Count
            FormAtteindre.TrackBar1.Maximum = FormAtteindre.NumericUpDownLigne.Maximum
            Dim No As Integer = Me.RichTextBox1.GetLineFromCharIndex(Me.RichTextBox1.SelectionStart) + 1
            If No > Me.RichTextBox1.Lines.Count Then No = Me.RichTextBox1.Lines.Count
            FormAtteindre.NumericUpDownLigne.Value = No
            FormAtteindre.TrackBar1.Value = No
            If FormAtteindre.ShowDialog() = Windows.Forms.DialogResult.OK Then AtteindreLigneAuto(CInt(FormAtteindre.NumericUpDownLigne.Value) - 1)
        Else
            MsgBox("Vous devez d'abord ouvrir un document!", MsgBoxStyle.Exclamation)
        End If
    End Sub

#End Region

#Region "Format"
    Public Sub IndentText(ByVal NbColonnes As Integer)
        'On veut faire la sélection des lignes complètes
        Dim iStart As Integer = Me.RichTextBox1.GetFirstCharIndexOfCurrentLine()
        Dim iEnd As Integer = iStart
        If Me.RichTextBox1.Text <> "" Then
            If Me.RichTextBox1.SelectionLength > 0 Then iEnd = Me.RichTextBox1.SelectionStart + Me.RichTextBox1.SelectionLength - 1
            If RichTextBox1.Text(iEnd) = Chr(10) Then iEnd -= 1
            Dim iLigne As Integer = Me.RichTextBox1.GetLineFromCharIndex(iEnd)
            iEnd = Me.RichTextBox1.GetFirstCharIndexFromLine(iLigne) + Me.RichTextBox1.Lines(iLigne).Length
            Me.RichTextBox1.SelectionStart = iStart
            Me.RichTextBox1.SelectionLength = iEnd - iStart
            'Faire l'indentation
            Dim NouvText As String = Commun.Indent(Me.RichTextBox1.SelectedText, NbColonnes)
            Me.RichTextBox1.SelectedText = NouvText
            Me.RichTextBox1.SelectionStart = iStart
            Me.RichTextBox1.SelectionLength = NouvText.Length
            AjouterHistoriqueMacro("scpEdit.IndentText(" & NbColonnes & ")")
        End If
    End Sub
#End Region

#Region "Marqueurs"

    Public Sub NouveauMarqueurAuto(ByVal Titre As String, ByVal Masque As String, ByVal CoulFP As String, ByVal CoulFS As String, ByVal CoulTP As String, ByVal CoulTS As String, ByVal bCasse As Boolean, ByVal bPropager As Boolean, ByVal bSouligner As Boolean, ByVal bAutoCoul As Boolean, ByVal Modele As String, ByVal Condition As String)
        'Version non interactive de création d'un nouveau marqueur
        Dim No As Integer = 2
        Dim oMarqueur As New ClassMarqueur(Titre)
        Do While Me.ProjetCourant.ColMarqueurs.Contains(Titre)
            Titre = oMarqueur.Titre & No.ToString
            No += 1
        Loop
        oMarqueur.Titre = Titre
        oMarqueur.sMasque = Masque
        oMarqueur.CoulFondPrimaire = CoulFP
        oMarqueur.CoulFondSecondaire = CoulFS
        oMarqueur.CoulTextePrimaire = CoulTP
        oMarqueur.CoulTexteSecondaire = CoulTS
        oMarqueur.SensibleCasse = bCasse.ToString
        oMarqueur.Propager = bPropager.ToString
        oMarqueur.Souligne = bSouligner.ToString
        oMarqueur.AutoCoulTextePrimaire = bAutoCoul.ToString
        oMarqueur.Modele = Modele
        oMarqueur.Condition = Condition
        Dim oItem As ListViewItem = Me.ListViewMarqueurs.Items.Add(oMarqueur.Titre, oMarqueur.Titre, "")
        oItem.SubItems.Add("")
        oItem.Tag = oMarqueur
        oItem.Checked = True
        oItem.ToolTipText = oMarqueur.Masque
        oItem.BackColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulFondPrimaire)
        oItem.ForeColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulTextePrimaire)
        Call Me.RechercherMarqueurs()
    End Sub

    Private Sub NouveauMarqueur()
        Dim Nom As String = "Nouveau"
        Dim No As Integer = 0
        While Me.ListViewMarqueurs.Items.ContainsKey(Nom)
            No += 1
            Nom = "Nouveau" & No.ToString("0")
        End While
        Dim oNewMasque As New ClassMarqueur(Nom)
        If oNewMasque.Edition() Then
            Dim oItem As ListViewItem = ListViewMarqueurs.Items.Add(oNewMasque.Titre, oNewMasque.Titre, "")
            oItem.Checked = True
            oItem.Tag = oNewMasque
            oItem.SubItems.Add("")
            oItem.ToolTipText = oNewMasque.Masque
            oItem.BackColor = System.Drawing.ColorTranslator.FromHtml(oNewMasque.CoulFondPrimaire)
            oItem.ForeColor = System.Drawing.ColorTranslator.FromHtml(oNewMasque.CoulTextePrimaire)
            RechercherMarqueurs()
            Dim oAuto As New ClassAuto
            Dim cmd As String = "scpedit.NouveauMarqueur("
            cmd &= Chr(34) & oNewMasque.Titre & Chr(34) & ","
            cmd &= Chr(34) & oNewMasque.Masque & Chr(34) & ","
            cmd &= Chr(34) & oNewMasque.CoulFondPrimaire & Chr(34) & ","
            cmd &= Chr(34) & oNewMasque.CoulFondSecondaire & Chr(34) & ","
            cmd &= Chr(34) & oNewMasque.CoulTextePrimaire & Chr(34) & ","
            cmd &= Chr(34) & oNewMasque.CoulTexteSecondaire & Chr(34) & ","
            cmd &= oNewMasque.SensibleCasse.ToString & ","
            cmd &= oNewMasque.Propager.ToString & ","
            cmd &= oNewMasque.Souligne.ToString & ","
            cmd &= oNewMasque.AutoCoulTextePrimaire.ToString & ","
            cmd &= Chr(34) & oNewMasque.Modele & Chr(34) & ","
            cmd &= Chr(34) & oNewMasque.Condition & Chr(34) & ",)"
            AjouterHistoriqueMacro(cmd)
        End If
    End Sub

    Private Sub DeleteItemRecherche()
        If Me.ListViewMarqueurs.SelectedItems.Count = 1 Then
            Dim oItem As ListViewItem = Me.ListViewMarqueurs.SelectedItems(0)
            AjouterHistoriqueMacro("scpEdit.SupprimerMarqueur(" & Chr(34) & oItem.Text & Chr(34) & ")")
            oItem.Remove()
        ElseIf Me.ListViewMarqueurs.SelectedItems.Count > 1 Then
            If MsgBox("Supprimer tous les marqueurs ?", MsgBoxStyle.Question Or MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
                AjouterHistoriqueMacro("scpEdit.SupprimerTousMarqueur()")
                Me.ListViewMarqueurs.Items.Clear()
            End If
        End If
    End Sub

    Public Sub RechercherMarqueurs()
        Dim oOldItem = oItemCourant
        Me.Cursor = Cursors.WaitCursor
        Me.RichTextBox1.Visible = False
        Me.RichTextBox1.SuspendLayout()
        Me.iChaineTrouvee = 0
        'Faire les recherches
        'Call Me.AfficherStatistiquesGlobales()
        Me.ToolStripProgressBar1.Maximum = Me.ListViewFichiers.Items.Count + 1
        Me.ToolStripProgressBar1.Minimum = 0
        Me.ToolStripProgressBar1.Value = 0
        Me.ToolStripProgressBar1.Visible = True
        For Each oItem As ListViewItem In Me.ListViewFichiers.Items
            Me.AfficheCourant(oItem)
            Me.RechercherMarqeursDocCourant()
            Me.ToolStripProgressBar1.Value += 1
            My.Application.DoEvents()
        Next
        'Statistiques
        Call Me.AfficherStatistiquesGlobales()
        'Reactualiser l'affichage
        Me.ToolStripProgressBar1.Visible = False
        Me.RichTextBox1.ResumeLayout()
        Me.AfficheCourant(oOldItem)
        If Not DocumentCourant Is Nothing Then RichTextBox1.Visible = True
        Me.Cursor = Cursors.Default
        AjouterHistoriqueMacro("scpEdit.MajMarqueurs()")
    End Sub

    Private Sub MarquerStyle(ByVal Marquer As Boolean)
        If Not RichTextBox1.SelectionFont Is Nothing Then
            Dim currentFont As System.Drawing.Font = RichTextBox1.Font
            Dim newFontStyle As System.Drawing.FontStyle
            If Marquer Then
                newFontStyle = FontStyle.Underline
            Else
                newFontStyle = FontStyle.Regular
            End If
            RichTextBox1.SelectionFont = New Font(currentFont.FontFamily, currentFont.Size, newFontStyle)
        End If
    End Sub

    Public Sub RechercherMarqeursDocCourant()
        'On reprend le code complet des méthodes Marquer et Extraire de la classe marqueur pour
        'des raisons de performance. On va boucler une seule fois sur les matchs...
        'Vider les résultats précédents
        Dim oldPos As Integer = Me.RichTextBox1.SelectionStart
        Dim oldLength As Integer = Me.RichTextBox1.SelectionLength
        Dim iPosMarque As Integer = 0
        Me.RichTextBox1.SelectAll()
        MarquerStyle(False)
        Me.RichTextBox1.SelectionColor = Color.Black
        Me.RichTextBox1.SelectionBackColor = Color.Transparent
        If Not Me.DocumentCourant Is Nothing Then Me.DocumentCourant.iTrouve = 0
        Me.RichTextBox1.SelectionStart = 0
        Dim oColMatch As System.Text.RegularExpressions.MatchCollection
        Me.DocumentCourant.ClearStats()
        'Nouveau
        Me.RichTextBoxMarque.Text = ""
        'Fin Nouveau
        For Each oItem As ListViewItem In Me.ListViewMarqueurs.CheckedItems
            Dim oMasque As ClassMarqueur = oItem.Tag
            Dim Options As RegexOptions = RegexOptions.Multiline
            If oMasque.SensibleCasse = Boolean.FalseString Then Options = Options Or RegexOptions.IgnoreCase
            If oMasque.Multi = Boolean.TrueString Then Options = Options Or RegexOptions.Singleline
            Try
                oColMatch = System.Text.RegularExpressions.Regex.Matches(Me.RichTextBox1.Text, oMasque.Masque, Options)
            Catch ex As Exception
                MsgBox("Expression régulière invalide " & oMasque.Masque, MsgBoxStyle.Exclamation)
                Exit Sub
            End Try
            Dim CoulFP As Color = System.Drawing.ColorTranslator.FromHtml(oMasque.CoulFondPrimaire)
            Dim CoulFS As Color = System.Drawing.ColorTranslator.FromHtml(oMasque.CoulFondSecondaire)
            Dim CoulTP As Color = System.Drawing.ColorTranslator.FromHtml(oMasque.CoulTextePrimaire)
            Dim CoulTS As Color = System.Drawing.ColorTranslator.FromHtml(oMasque.CoulTexteSecondaire)
            Dim oCode As New ClassMacro
            If Not DocumentCourant.Stats.ContainsKey(oMasque.Titre) Then DocumentCourant.Stats.Add(oMasque.Titre, CInt(oColMatch.Count))
            For Each oMatch As Match In oColMatch
                'On a trouvé un match
                'TEST CONDITION VB
                Dim bRetenu As Boolean = True
                If oMasque.Condition <> "" Then bRetenu = oCode.EvalCondition(oMatch, oMasque.Condition)
                If bRetenu Then
                    Me.DocumentCourant.iTrouve += 1
                    'Debug.Print(oMasque.Titre & " = " & oMasque.Compteur)
                    oMasque.IncCompteur()
                    Me.iChaineTrouvee += 1
                    iPosMarque = Me.RichTextBoxMarque.TextLength
                    Dim sFormate As String = oMasque.Modele
                    sFormate = Regex.Replace(sFormate, "\$Fichier", DocumentCourant.Titre, RegexOptions.IgnoreCase)
                    sFormate = Regex.Replace(sFormate, "\$Chemin", DocumentCourant.Chemin, RegexOptions.IgnoreCase)
                    sFormate = Regex.Replace(sFormate, "\$No", oMatch.Index.ToString("0"), RegexOptions.IgnoreCase)
                    For iSubMatch As Integer = 0 To oMatch.Groups.Count - 1
                        sFormate = sFormate.Replace("$" & iSubMatch.ToString("0"), oMatch.Groups(iSubMatch).Value)
                    Next
                    Me.RichTextBoxMarque.AppendText(sFormate)
                    For iIndex As Integer = 0 To oMatch.Groups.Count - 1
                        Me.RichTextBox1.Select(oMatch.Groups(iIndex).Index, oMatch.Groups(iIndex).Length)
                        If iIndex = 0 Then
                            'Match
                            Me.RichTextBox1.SelectionColor = CoulTP
                            If Commun.TestRegex(oMatch.Value, "#[0-9a-f]{6}") And (oMasque.AutoCoulTextePrimaire = Boolean.TrueString) Then
                                Me.RichTextBox1.SelectionColor = System.Drawing.ColorTranslator.FromHtml(oMatch.Value)
                            End If
                            Me.RichTextBox1.SelectionBackColor = CoulFP
                            If oMasque.Souligne = Boolean.TrueString Then MarquerStyle(True)
                        Else
                            'SubMatch
                            If oMasque.Souligne = Boolean.TrueString Then MarquerStyle(True)
                            Me.RichTextBox1.SelectionColor = System.Drawing.ColorTranslator.FromHtml(oMasque.CoulTexteSecondaire)
                            'On alterne la couleur avec deux tons plus bas pour distinguer les submatch collés
                            If iIndex Mod 2 = 0 Then
                                Me.RichTextBox1.SelectionBackColor = CoulFS
                            Else
                                Me.RichTextBox1.SelectionBackColor = ControlPaint.LightLight(CoulFS)
                            End If
                            'Propagation
                            If oMasque.Propager = Boolean.TrueString And oMatch.Groups(iIndex).Value <> "" Then
                                Dim iStart As Integer = 1
                                Dim iPos As Integer
                                Do
                                    iPos = Me.RichTextBox1.Text.IndexOf(oMatch.Groups(iIndex).Value, iStart)
                                    If iPos <> -1 Then
                                        Me.RichTextBox1.Select(iPos, oMatch.Groups(iIndex).Length)
                                        If oMasque.Souligne = Boolean.TrueString Then MarquerStyle(True)
                                        Me.RichTextBox1.SelectionColor = CoulTS
                                        If iIndex Mod 2 = 0 Then
                                            Me.RichTextBox1.SelectionBackColor = CoulFS
                                        Else
                                            Me.RichTextBox1.SelectionBackColor = ControlPaint.LightLight(CoulFS)
                                        End If
                                        iStart = iPos + 1
                                    End If
                                Loop Until iPos = -1
                            End If
                        End If
                    Next
                    Me.RichTextBoxMarque.AppendText(vbCrLf)
                End If
            Next
            'Debug.Print(oMasque.Titre & "=" & oMasque.Compteur)
        Next 'Marqueur
        If Me.DocumentCourant.iTrouve > 0 Then
            oItemCourant.SubItems(1).Text = Me.DocumentCourant.iTrouve.ToString("0")
        Else
            oItemCourant.SubItems(1).Text = ""
        End If
        oItemCourant.ImageKey = DocumentCourant.GetIconeName()
        Me.UpdateCompteurs()
        Me.UpdateStatus()
        Me.RichTextBox1.SelectionStart = oldPos
        Me.RichTextBox1.SelectionLength = oldLength
    End Sub

    Private Sub AjouterAMarqueurs()
        If Me.RichTextBox1.SelectedText <> "" Then
            Dim oMasque As New ClassMarqueur
            Dim sTexte As String = Me.RichTextBox1.SelectedText
            'On utilise toute la sélection comme texte d'essai
            oMasque.TestTexte = sTexte
            'On limite le masque à une ligne
            If sTexte.Contains(vbLf) Then sTexte = sTexte.Substring(0, sTexte.IndexOf(vbLf))
            'On essai de limiter la taille du masque
            If sTexte.Length > 64 Then sTexte = sTexte.Substring(0, 64) & ".*"
            oMasque.sMasque = sTexte
            'On tente de définir un titre formé des 3 premiers mots au maximum...
            Dim Titre As String = Commun.ExtrairePremiersMots(sTexte, 3)
            Dim No As Integer = 0
            If Titre = "" Then Titre = "Nouveau"
            oMasque.Titre = Titre
            While Me.ListViewMarqueurs.Items.ContainsKey(oMasque.Titre)
                No += 1
                oMasque.Titre = Titre & No.ToString("0")
            End While
            Me.RichTextBox1.SelectionLength = 0
            'On choisi une couleur par défaut
            oMasque.CoulFondPrimaire = Me.GetDefaultCoul("")
            oMasque.CoulFondSecondaire = Me.GetCoulComp(oMasque.CoulFondPrimaire)
            If oMasque.Edition() Then
                Dim oItem As ListViewItem = Me.ListViewMarqueurs.Items.Add(oMasque.Titre, oMasque.Titre, "")
                oItem.SubItems.Add("")
                oItem.Tag = oMasque
                oItem.Checked = True
                oItem.ToolTipText = oMasque.Masque
                oItem.BackColor = System.Drawing.ColorTranslator.FromHtml(oMasque.CoulFondPrimaire)
                oItem.ForeColor = System.Drawing.ColorTranslator.FromHtml(oMasque.CoulTextePrimaire)
                'oItem.SubItems(0).BackColor = System.Drawing.ColorTranslator.FromHtml(oMasque.CoulFondSecondaire)
                'oItem.SubItems(0).ForeColor = System.Drawing.ColorTranslator.FromHtml(oMasque.CoulTexteSecondaire)
                Call Me.RechercherMarqueurs()
                Dim cmd As String = "scpedit.NouveauMarqueur("
                cmd &= Chr(34) & oMasque.Titre & Chr(34) & ","
                cmd &= Chr(34) & oMasque.Masque & Chr(34) & ","
                cmd &= Chr(34) & oMasque.CoulFondPrimaire & Chr(34) & ","
                cmd &= Chr(34) & oMasque.CoulFondSecondaire & Chr(34) & ","
                cmd &= Chr(34) & oMasque.CoulTextePrimaire & Chr(34) & ","
                cmd &= Chr(34) & oMasque.CoulTexteSecondaire & Chr(34) & ","
                cmd &= oMasque.SensibleCasse.ToString & ","
                cmd &= oMasque.Propager.ToString & ","
                cmd &= oMasque.Souligne.ToString & ","
                cmd &= oMasque.AutoCoulTextePrimaire.ToString & ","
                cmd &= Chr(34) & oMasque.Modele & Chr(34) & ","
                cmd &= Chr(34) & oMasque.Condition & Chr(34) & ",)"
                AjouterHistoriqueMacro(cmd)
            End If
        Else
            MsgBox("Vous devez d'abord sélectionner le texte à ajouter comme nouveau marqueur!", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub DupliquerMarqueurCourant()
        If Me.ListViewMarqueurs.SelectedItems.Count > 0 Then
            Dim oMarqueurSource As ClassMarqueur = Me.ListViewMarqueurs.SelectedItems(0).Tag
            Dim Nom As String = oMarqueurSource.Titre
            Dim Prefix As String = oMarqueurSource.Titre
            Dim No As Integer = 1
            Dim oMatch As System.Text.RegularExpressions.Match = System.Text.RegularExpressions.Regex.Match(Prefix, "\d+")
            If oMatch.Success Then
                No = Val(oMatch.Value)
                Prefix = Nom.Replace(No.ToString, "")
            End If
            No = No + 1
            Nom = Prefix & No.ToString("0")
            While Me.ListViewMarqueurs.Items.ContainsKey(Nom)
                No += 1
                Nom = Prefix & No.ToString("0")
            End While
            Dim oNewMasque As New ClassMarqueur(Nom)
            oNewMasque.sMasque = oMarqueurSource.sMasque
            oNewMasque.SensibleCasse = oMarqueurSource.SensibleCasse
            oNewMasque.Propager = oMarqueurSource.Propager
            oNewMasque.Souligne = oMarqueurSource.Souligne
            oNewMasque.TestTexte = oMarqueurSource.TestTexte
            oNewMasque.CoulFondPrimaire = Me.GetDefaultCoul("")
            oNewMasque.CoulFondSecondaire = Me.GetCoulComp(oNewMasque.CoulFondPrimaire)
            If oNewMasque.Edition() Then
                Dim oItem As ListViewItem = ListViewMarqueurs.Items.Add(oNewMasque.Titre, oNewMasque.Titre, "")
                oItem.Checked = True
                oItem.Tag = oNewMasque
                oItem.ToolTipText = oNewMasque.Masque
                oItem.SubItems.Add("")
                oItem.BackColor = System.Drawing.ColorTranslator.FromHtml(oNewMasque.CoulFondPrimaire)
                oItem.ForeColor = System.Drawing.ColorTranslator.FromHtml(oNewMasque.CoulTextePrimaire)
                RechercherMarqueurs()
            End If
        Else
            MsgBox("Veuillez d'abord sélectionner le marqueur à dupliquer!", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub EditMasqueCourant()
        If Me.ListViewMarqueurs.SelectedItems.Count > 0 Then
            Dim oItem As ListViewItem = Me.ListViewMarqueurs.SelectedItems(0)
            Dim oMarqueur As ClassMarqueur = oItem.Tag
            oMarqueur.Edition()
            oMarqueur.ResetCompteur()
            oItem.Name = oMarqueur.Titre
            oItem.Text = oMarqueur.Titre
            oItem.ToolTipText = oMarqueur.Masque
            oItem.BackColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulFondPrimaire)
            oItem.ForeColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulTextePrimaire)
            'Updater tous les tooltips a cause des maqueurs imbriqués
            For Each oItem2 As ListViewItem In Me.ListViewMarqueurs.Items
                oItem2.ToolTipText = oItem2.Tag.Masque
            Next
            RechercherMarqueurs()
        Else
            MsgBox("Veuillez d'abord sélectionner le marqueur à modifier!", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Public Sub UpdateCompteurs()
        'Afficher les compteurs
        For Each oItem As ListViewItem In Me.ListViewMarqueurs.Items
            Dim oMasque As ClassMarqueur = oItem.Tag
            If oItem.SubItems.Count < 1 Then oItem.SubItems.Add(" ")
            If oItem.SubItems.Count < 2 Then oItem.SubItems.Add(" ")
            If Not oMasque Is Nothing Then
                If oMasque.Compteur = 0 Then
                    oItem.SubItems(1).Text = ""
                Else
                    oItem.SubItems(1).Text = oMasque.Compteur.ToString("0")
                End If
            End If
        Next
    End Sub

    Public Sub AllerSuivant()
        'On défini le point de départ
        Dim iPos As Integer = Me.RichTextBox1.SelectionStart
        If Me.RichTextBox1.SelectionLength > 0 Then iPos += Me.RichTextBox1.SelectionLength
        'On défini la position du dernier trouvé
        Dim iPosTrouve As Integer = Me.RichTextBox1.Text.Length
        Dim iLenghtTrouve As Integer = 0
        Dim oItemCol As Object = Me.ListViewMarqueurs.CheckedItems
        If Me.ListViewMarqueurs.SelectedItems.Count > 0 Then oItemCol = Me.ListViewMarqueurs.SelectedItems
        For Each oItemMarqueur As ListViewItem In oItemCol
            Dim oMarqueur As ClassMarqueur = oItemMarqueur.Tag
            Dim Options As RegexOptions = RegexOptions.Multiline
            If oMarqueur.SensibleCasse = Boolean.FalseString Then Options = Options Or RegexOptions.IgnoreCase
            For Each oMatch As Match In Regex.Matches(Me.RichTextBox1.Text, oMarqueur.Masque, Options)
                If (oMatch.Index > iPos) And (oMatch.Index < iPosTrouve) Then
                    iPosTrouve = oMatch.Index
                    iLenghtTrouve = oMatch.Length
                End If
            Next
        Next
        If iPosTrouve = Me.RichTextBox1.Text.Length Then iPosTrouve = 0
        Me.RichTextBox1.SelectionStart = iPosTrouve
        Me.RichTextBox1.SelectionLength = iLenghtTrouve
        Me.RichTextBox1.Focus()
        AjouterHistoriqueMacro("scpEdit.AllerSuivant()")
    End Sub

    Public Sub AllerPrecedent()
        'On défini le point de départ
        Dim iPos As Integer = Me.RichTextBox1.SelectionStart
        If Me.RichTextBox1.SelectionLength > 0 Then iPos -= 1
        'On défini la position du dernier trouvé
        Dim iPosTrouve As Integer = 0
        Dim iLenghtTrouve As Integer = 0
        Dim oItemCol As Object = Me.ListViewMarqueurs.CheckedItems
        If Me.ListViewMarqueurs.SelectedItems.Count > 0 Then oItemCol = Me.ListViewMarqueurs.SelectedItems
        For Each oItemMarqueur As ListViewItem In oItemCol
            Dim oMarqueur As ClassMarqueur = oItemMarqueur.Tag
            Dim Options As RegexOptions = RegexOptions.Multiline
            If oMarqueur.SensibleCasse = Boolean.FalseString Then Options = Options Or RegexOptions.IgnoreCase
            For Each oMatch As Match In Regex.Matches(RichTextBox1.Text, oMarqueur.Masque, Options)
                If (oMatch.Index < iPos) And (oMatch.Index > iPosTrouve) Then
                    iPosTrouve = oMatch.Index
                    iLenghtTrouve = oMatch.Length
                End If
            Next
        Next
        If iPosTrouve = 0 Then iPosTrouve = Me.RichTextBox1.Text.Length
        Me.RichTextBox1.SelectionStart = iPosTrouve
        Me.RichTextBox1.SelectionLength = iLenghtTrouve
        Me.RichTextBox1.Focus()
        AjouterHistoriqueMacro("scpEdit.AllerPrecedent()")
    End Sub

    Private Sub RemonterMarqueur()
        If Me.ListViewMarqueurs.SelectedItems.Count > 0 Then
            Dim oItem As ListViewItem = Me.ListViewMarqueurs.SelectedItems(0)
            If oItem.Index > 0 Then
                Dim iIndex As Integer = oItem.Index - 1
                oItem.Remove()
                Me.ListViewMarqueurs.Items.Insert(iIndex, oItem)
                oItem.Selected = True
                Me.ListViewMarqueurs.Focus()
            End If
        End If
    End Sub

    Private Sub DescendreMarqueur()
        If Me.ListViewMarqueurs.SelectedItems.Count > 0 Then
            Dim oItem As ListViewItem = Me.ListViewMarqueurs.SelectedItems(0)
            If oItem.Index < Me.ListViewMarqueurs.Items.Count - 1 Then
                Dim iIndex As Integer = oItem.Index + 1
                oItem.Remove()
                Me.ListViewMarqueurs.Items.Insert(iIndex, oItem)
                oItem.Selected = True
                Me.ListViewMarqueurs.Focus()
            End If
        End If
    End Sub

#End Region

#Region "Inserer"

    Private Sub InsertFragment()
        If FormFragment.ShowDialog() = Windows.Forms.DialogResult.OK Then
            If Me.DocumentCourant Is Nothing Then Me.Nouveau()
            'Insertion
            My.Application.DoEvents()
            Me.Cursor = Cursors.WaitCursor
            RichTextBox1.SelectedText = FormFragment.TextBox1.Text
            RichTextBox1.Refresh()
            My.Application.DoEvents()
            Me.Cursor = Cursors.Default
            AjouterHistoriqueMacro("scpEdit.InsererTexte(scpEdit.GetFragment(" & Chr(34) & FormFragment.ComboBox1.Text & Chr(34) & "))")
        End If
    End Sub
    Private Sub InsererDate()
        If Not Me.DocumentCourant Is Nothing Then
            Me.RichTextBox1.SelectedText = Now().ToString("d")
            AjouterHistoriqueMacro("scpEdit.InsererTexte(date())")
        Else
            MsgBox("Vous devez d'abord ouvrir un document!", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub InsererDateHeure()
        If Not Me.DocumentCourant Is Nothing Then
            Me.RichTextBox1.SelectedText = Now().ToString("g")
            AjouterHistoriqueMacro("scpEdit.InsererTexte(Now())")
        Else
            MsgBox("Vous devez d'abord ouvrir un document!", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub InsererUtilisateur()
        If Not Me.DocumentCourant Is Nothing Then
            Me.RichTextBox1.SelectedText = My.User.Name
            AjouterHistoriqueMacro("scpEdit.InsererTexte(scpEdit.GetUser())")
        Else
            MsgBox("Vous devez d'abord ouvrir un document!", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub InsererComputer()
        If Not Me.DocumentCourant Is Nothing Then
            Me.RichTextBox1.SelectedText = My.Computer.Name
            AjouterHistoriqueMacro("scpEdit.InsererTexte(scpEdit.GetComputer())")
        Else
            MsgBox("Vous devez d'abord ouvrir un document!", MsgBoxStyle.Exclamation)
        End If

    End Sub

    Private Sub InsererNomFichier()
        If Not Me.DocumentCourant Is Nothing Then
            Me.OpenFileDialog1.Multiselect = True
            If Me.OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                Me.RichTextBox1.SelectedText = String.Join(vbCrLf, Me.OpenFileDialog1.FileNames())
            End If
        Else
            MsgBox("Vous devez d'abord ouvrir un document!", MsgBoxStyle.Exclamation)
        End If

    End Sub

    Private Sub InsererFichier()
        If Not Me.DocumentCourant Is Nothing Then
            Me.OpenFileDialog1.Multiselect = True
            If Me.OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                For Each sFichier As String In Me.OpenFileDialog1.FileNames()
                    Try
                        Me.RichTextBox1.SelectedText = My.Computer.FileSystem.ReadAllText(sFichier, System.Text.Encoding.Default) & vbCrLf
                        Me.RichTextBox1.SelectionStart = Me.RichTextBox1.SelectionStart + Me.RichTextBox1.SelectionLength
                        AjouterHistoriqueMacro("scpEdit.InsererTexte(scpEdit.LireFichier(" & Chr(34) & sFichier & Chr(34) & "))")
                    Catch Ex As Exception
                        MsgBox("Erreur à la lecture du fichier " & sFichier & ": " & Ex.Message, MsgBoxStyle.Exclamation)
                    End Try
                Next
            End If
        Else
            MsgBox("Vous devez d'abord ouvrir un document!", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub InsererShell()
        Dim sArgs As String = Me.RichTextBox1.SelectedText
        If (sArgs = "") Then
            'On capture la ligne courante
            Dim NoLigne As Integer = Me.RichTextBox1.GetLineFromCharIndex(Me.RichTextBox1.SelectionStart)
            sArgs = Me.RichTextBox1.Lines(NoLigne)
            'On se positionne à la fin de la ligne courante ou du fichier
            If NoLigne < (Me.RichTextBox1.Lines.Count - 1) Then
                Me.RichTextBox1.SelectionStart = Me.RichTextBox1.GetFirstCharIndexFromLine(NoLigne + 1)
            Else
                Me.RichTextBox1.SelectionStart = Me.RichTextBox1.TextLength
            End If
        End If
        'Résultats dans un nouveau document ?
        If Me.RésultatsDesCommandesDansUnNouveauDocumentToolStripMenuItem.Checked Then Call Me.Nouveau()
        'On y va
        If sArgs <> "" Then
            'Inserer le résultat
            If Me.RichTextBox1.SelectionLength = 0 Then Me.RichTextBox1.SelectedText = vbCrLf
            Me.RichTextBox1.SelectedText = Commun.RunShell(sArgs)
        End If
        Me.RichTextBox1.ScrollToCaret()
    End Sub

    Private Sub InsererPowerShell()
        Dim sArgs As String = Me.RichTextBox1.SelectedText
        If (sArgs = "") Then
            'On capture la ligne courante
            Dim NoLigne As Integer = Me.RichTextBox1.GetLineFromCharIndex(Me.RichTextBox1.SelectionStart)
            sArgs = Me.RichTextBox1.Lines(NoLigne)
            'On se positionne à la fin de la ligne courante ou du fichier
            If NoLigne < (Me.RichTextBox1.Lines.Count - 1) Then
                Me.RichTextBox1.SelectionStart = Me.RichTextBox1.GetFirstCharIndexFromLine(NoLigne + 1)
            Else
                Me.RichTextBox1.SelectionStart = Me.RichTextBox1.TextLength
            End If
        End If
        'Résultats dans un nouveau document ?
        If Me.RésultatsDesCommandesDansUnNouveauDocumentToolStripMenuItem.Checked Then Call Me.Nouveau()
        'On y va
        If sArgs <> "" Then
            'Inserer le résultat
            If Me.RichTextBox1.SelectionLength = 0 Then Me.RichTextBox1.SelectedText = vbCrLf
            Me.RichTextBox1.SelectedText = Commun.RunPowerShell(sArgs)
        End If
        Me.RichTextBox1.ScrollToCaret()
    End Sub

    Private Sub InsererCode()
        'Préparer la commande
        Dim sArgs As String = Me.RichTextBox1.SelectedText
        'On autorise le multiligne seulement pour le vbscript
        'Si on n'a pas de sélection alors on se rabat sur la ligne courante
        If (sArgs = "") Then
            'On capture la ligne courante
            Dim NoLigne As Integer = Me.RichTextBox1.GetLineFromCharIndex(Me.RichTextBox1.SelectionStart)
            sArgs = Me.RichTextBox1.Lines(NoLigne)
            'On se positionne à la fin de la ligne courante ou du fichier
            If NoLigne < (Me.RichTextBox1.Lines.Count - 1) Then
                Me.RichTextBox1.SelectionStart = Me.RichTextBox1.GetFirstCharIndexFromLine(NoLigne + 1)
            Else
                Me.RichTextBox1.SelectionStart = Me.RichTextBox1.TextLength
            End If
        End If
        'Résultats dans un nouveau document ?
        If Me.RésultatsDesCommandesDansUnNouveauDocumentToolStripMenuItem.Checked Then Call Me.Nouveau()
        'On y va
        If sArgs <> "" Then
            'Creer un objet code temporaire
            Dim oCode As New ClassMacro
            oCode.Titre = "TempCode"
            oCode.Code = sArgs
            'Ajustement le code vbscript pour permettre l'affichage
            Dim sUpper As String = oCode.Code.ToUpper
            If Not (sUpper.Contains("WSCRIPT.ECHO") Or sUpper.Contains("SCPEDIT.AJOUTER") Or sUpper.Contains("SCPEDIT.INSERER")) Then
                If Me.RichTextBox1.SelectionLength > 0 Then
                    oCode.Code = "scpEdit.RemplacerTexte " & oCode.Code
                Else
                    oCode.Code = "scpEdit.InsererTexte " & oCode.Code
                End If
            End If
            Dim sortie As String = oCode.Execute()
            If sortie.Contains("ERREUR!") Then Me.RichTextBox1.SelectedText = vbCrLf & sortie
            Me.RichTextBox1.ScrollToCaret()
            oCode = Nothing
        End If
    End Sub
#End Region

#Region "Impression"

    Private Sub Appercu()
        If (PrintPreviewDialog1.ShowDialog = DialogResult.OK) Then
            PrintDocument1.Print()
        End If
        AjouterHistoriqueMacro("'Apperçu avant impression : Non disponible en macros")
    End Sub

    Public Sub IMprimerTousAuto()
        For Each oItem As ListViewItem In Me.ListViewFichiers.Items
            AfficheCourant(oItem)
            'Lancement de l'impression
            Me.PrintDocument1.PrinterSettings = Me.PrintDialog1.PrinterSettings
            Me.PrintDocument1.PrinterSettings.DefaultPageSettings.Margins.Top = 50
            Me.PrintDocument1.PrinterSettings.DefaultPageSettings.Margins.Left = 50
            Me.PrintDocument1.Print()
        Next
        AjouterHistoriqueMacro("scpEdit.ImprimerTous()")
    End Sub

    Private Sub ImprimerTous()
        If Me.PrintDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            IMprimerTousAuto()
        End If
    End Sub

    Public Sub ImprimerCourantAuto()
        'Version non interactive
        If Not Me.DocumentCourant Is Nothing Then
            'Lancement de l'impression
            Me.PrintDocument1.PrinterSettings = Me.PrintDialog1.PrinterSettings
            Me.PrintDocument1.PrinterSettings.DefaultPageSettings.Margins.Top = 50
            Me.PrintDocument1.PrinterSettings.DefaultPageSettings.Margins.Left = 50
            Me.PrintDocument1.Print()
            AjouterHistoriqueMacro("scpEdit.ImprimerCourant()")
        End If
    End Sub

    Private Sub ImprimerCourant()
        'Lancer l'impression du document courant
        If Not Me.DocumentCourant Is Nothing Then
            If Me.PrintDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
                ImprimerCourantAuto()
            End If
        Else
            MsgBox("Il n'y a aucun élément à imprimer", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub PrintDocument1_BeginPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.BeginPrint
        ' Start at the beginning of the text
        Me.PageNumber = 1
        Me.DateImpression = Now().ToString("g")
        m_nFirstCharOnPage = 0
    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        'Entete sur toutes les pages
        Dim MargeHaut As Integer = PrintDocument1.DefaultPageSettings.Margins.Top
        Dim MargeBas As Integer = PrintDocument1.DefaultPageSettings.Bounds.Bottom - PrintDocument1.DefaultPageSettings.Margins.Bottom
        Dim MargeGauche As Integer = PrintDocument1.DefaultPageSettings.Margins.Left
        Dim MargeDroite As Integer = PrintDocument1.DefaultPageSettings.Bounds.Right - PrintDocument1.DefaultPageSettings.Margins.Right
        Dim oFormatDroit As New System.Drawing.StringFormat
        oFormatDroit.Alignment = StringAlignment.Far
        Dim oTitle1Font As New Font("Verdana", 10, FontStyle.Italic)
        e.Graphics.DrawString(Me.DocumentCourant.Chemin, oTitle1Font, Brushes.Black, MargeGauche, MargeHaut - oTitle1Font.Height)
        e.Graphics.DrawString("Page " & Me.PageNumber.ToString("0"), oTitle1Font, Brushes.Black, MargeDroite, MargeHaut - oTitle1Font.Height, oFormatDroit)
        e.Graphics.DrawLine(Pens.Black, MargeGauche, MargeHaut - 1, MargeDroite, MargeHaut - 1)
        'e.Graphics.DrawRectangle(System.Drawing.Pens.Gray, e.MarginBounds)
        'Impression couleur du richtextbox via la classe Richtextboxex.
        m_nFirstCharOnPage = RichTextBox1.FormatRange(False, e, m_nFirstCharOnPage, RichTextBox1.TextLength)
        If (m_nFirstCharOnPage < RichTextBox1.TextLength) Then
            e.HasMorePages = True
            Me.PageNumber += 1
        Else
            e.HasMorePages = False
        End If
        'Bas de page
        e.Graphics.DrawLine(Pens.Black, MargeGauche, MargeBas + 1, MargeDroite, MargeBas + 1)
        e.Graphics.DrawString(Me.DateImpression, oTitle1Font, Brushes.Black, MargeDroite, MargeBas + oTitle1Font.Height, oFormatDroit)
    End Sub

    Private Sub PrintDocument1_EndPrint(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles PrintDocument1.EndPrint
        ' Clean up cached information
        RichTextBox1.FormatRangeDone()
    End Sub

#End Region

#Region "Projet"

    Private Sub OuvrirProjet()
        If Me.ListViewFichiers.Items.Count > 0 Then
            Dim iModif As Long = 0
            For Each oItem As ListViewItem In Me.ListViewFichiers.Items
                If oItem.Tag.Modifie Then iModif += 1
            Next
            If iModif > 0 Then
                Dim msg As String = "1 document a été modifié. Désirez-vous l'enregistrer avant d'ouvrir un projet ?"
                If iModif > 1 Then msg = iModif.ToString("0") & " documents ont été modifiés. Désirez-vous les enregistrer avant d'ouvrir un projet ?"
                If MsgBox(msg, MsgBoxStyle.OkCancel Or MsgBoxStyle.Question) = MsgBoxResult.Ok Then
                    DocumentCourant.Contenu = Me.RichTextBox1.Text
                    EnregistrerTous()
                End If
            End If
        End If
        Me.OpenFileDialog1.Filter = "Projet scpEdit|*.scp"
        Me.OpenFileDialog1.DefaultExt = ".scp"
        Me.OpenFileDialog1.Title = "Ouvrir un projet..."
        Me.OpenFileDialog1.Multiselect = False
        If My.Settings.DossierProjets <> "" Then
            If My.Computer.FileSystem.DirectoryExists(My.Settings.DossierProjets) Then Me.OpenFileDialog1.InitialDirectory = My.Settings.DossierProjets
        End If
        'On ne veut pas le nom par défaut...
        Me.OpenFileDialog1.FileName = ""
        If Me.OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            'On commence par fermer le projet courant
            If ProjetCourant.Chemin = sProjetTemp Then
                SaveProjet(ProjetCourant)
            Else
                EnregistrerProjet()
            End If
            FermerTous()
            ProjetCourant.Chemin = Me.OpenFileDialog1.FileName
            LoadProjet(ProjetCourant, True)
            My.Settings.ProjetOuvert = ProjetCourant.Chemin
            My.Settings.DossierProjets = My.Computer.FileSystem.GetParentPath(Me.OpenFileDialog1.FileName)
        End If
        Call Me.UpdateTitreFen()
    End Sub

    Private Sub EnregistrerProjet()
        If ProjetCourant.Chemin <> sProjetTemp Then
            Call SaveProjet(Me.ProjetCourant)
        Else
            Call EnregistrerProjetSous()
        End If
    End Sub

    Private Sub EnregistrerProjetSous()
        Me.SaveFileDialog1.Filter = "Projet scpEdit|*.scp"
        Me.SaveFileDialog1.Title = "Enregistrer projet sous..."
        Me.SaveFileDialog1.OverwritePrompt = True
        If My.Settings.DossierProjets <> "" Then
            If My.Computer.FileSystem.DirectoryExists(My.Settings.DossierProjets) Then Me.SaveFileDialog1.InitialDirectory = My.Settings.DossierProjets
        End If
        If Me.SaveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            'On enregistre le projet
            Me.ProjetCourant.Chemin = Me.SaveFileDialog1.FileName
            Call SaveProjet(Me.ProjetCourant)
            My.Settings.ProjetOuvert = ProjetCourant.Chemin
            My.Settings.DossierProjets = My.Computer.FileSystem.GetParentPath(Me.SaveFileDialog1.FileName)
        End If
        Me.UpdateTitreFen()
    End Sub

    Private Sub FermerProjet()
        If ProjetCourant.Chemin <> sProjetTemp Then
            For Each oMacro As ClassMacro In ProjetCourant.ColCode
                If Commun.TestRegex(oMacro.Titre, "Autoclose") Then
                    oMacro.Execute()
                    Exit For
                End If
            Next
            EnregistrerProjet()
            FermerTous()
            My.Settings.ProjetOuvert = ""
            ProjetCourant.Chemin = sProjetTemp
            LoadProjet(ProjetCourant, False)
        End If
        Call AfficherStatistiquesGlobales()
        Call Me.UpdateTitreFen()
    End Sub

    Public Sub LoadProjet(ByRef oProjet As ClassProjet, ByVal bLoadFiles As Boolean)
        'Lire le projet lui-même
        If My.Computer.FileSystem.FileExists(oProjet.Chemin) Then
            Me.Cursor = Cursors.WaitCursor
            Me.RichTextBox1.Visible = False
            Try
                Dim CheminCourant As String = oProjet.Chemin
                Commun.LoadXML(oProjet, CheminCourant)
                'Mettre à jour le chemin
                oProjet.Chemin = CheminCourant
            Catch ex As Exception
                MsgBox("Erreur à la lecture du projet: " & ex.Message)
                Exit Sub
            End Try
            'Affichage des marqueurs
            ListViewMarqueurs.SuspendLayout()
            ListViewMarqueurs.Items.Clear()
            For Each oMarqueur As ClassMarqueur In oProjet.ColMarqueurs
                oMarqueur.ResetCompteur()
                Dim oItem As ListViewItem = ListViewMarqueurs.Items.Add(oMarqueur.Titre, oMarqueur.Titre, "")
                oItem.SubItems.Add("")
                oItem.Checked = oMarqueur.Actif
                oItem.ToolTipText = oMarqueur.Masque
                oItem.Tag = oMarqueur
                oItem.BackColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulFondPrimaire)
                oItem.ForeColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulTextePrimaire)
                'oItem.SubItems(0).BackColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulFondSecondaire)
                'oItem.SubItems(0).ForeColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulTexteSecondaire)
            Next
            ListViewMarqueurs.ResumeLayout()
            'Affichage des transformations
            FormTransform.ColTextTransform = ProjetCourant.ColTextTransform
            FormTransform.ComboBox1.Items.Clear()
            For Each oTransform As ClassTextTransform In ProjetCourant.ColTextTransform
                FormTransform.ComboBox1.Items.Add(oTransform.Titre)
            Next
            'Affichage des commandes
            Me.ToolStripComboBoxCommand.Items.Clear()
            For Each oCode As ClassMacro In oProjet.ColCode
                Me.ToolStripComboBoxCommand.Items.Add(oCode.Titre)
            Next
            Me.ToolStripComboBoxCommand.Items.Add("")
            'Affichage des transformations scriptées
            FormFiltreScript.oColScripts = oProjet.ColFiltreScripts
            FormFiltreScript.ComboBox1.Items.Clear()
            For Each oScript As ClassMacro In oProjet.ColFiltreScripts
                FormFiltreScript.ComboBox1.Items.Add(oScript.Titre)
            Next
            'Affichage des fragments
            FormFragment.oColFragments = oProjet.ColFragments
            FormFragment.ComboBox1.Items.Clear()
            For Each oFragment As ClassFragment In oProjet.ColFragments
                FormFragment.ComboBox1.Items.Add(oFragment.Titre)
            Next
            'Lire les fichiers du projet
            If oProjet.ColArchives.Count > 0 And bLoadFiles Then
                ToolStripProgressBar1.Minimum = 1
                ToolStripProgressBar1.Maximum = oProjet.ColArchives.Count + 1
                ToolStripProgressBar1.Value = 1
                ToolStripProgressBar1.Visible = True
                For Each oArc As ClassArchive In oProjet.ColArchives
                    'Éviter de tenir compte de l'archive des fichiers sansnoms non enregistrés.
                    If oArc.CheminFichier.Trim() = "" Then
                        'On a un fichier non-enregistré
                        Nouveau()
                        DocumentCourant.Contenu = oArc.zContenu.GetValeur()
                        Me.RichTextBox1.Text = DocumentCourant.Contenu
                    Else
                        'On a un fichier réel
                        If Not ListViewFichiers.Items.ContainsKey(oArc.CheminFichier) Then
                            'Le fichier existe ?
                            If My.Computer.FileSystem.FileExists(oArc.CheminFichier) Then
                                OuvrirFichier(oArc.CheminFichier)
                                If oProjet.ColHisto.Contains(oArc.CheminFichier) Then DocumentCourant.Historique = oProjet.ColHisto(oArc.CheminFichier)
                                'Si le fichier est différent de la copie en archive, on pousse cette dernière dans l'historique
                                Dim sContenu As String = oArc.zContenu.GetValeur()
                                sContenu = sContenu.Replace(vbCrLf, vbLf)
                                If DocumentCourant.Contenu <> sContenu Then DocumentCourant.Historique.Push(oArc)
                            Else
                                'Non, alors on propose de récupérer l'archive
                                If MsgBox("Le fichier " & oArc.CheminFichier & " a été supprimé. Récupérer la dernière version enregistrée?", MsgBoxStyle.Question Or MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
                                    Dim oDoc As New ClassDocument(oArc.CheminFichier, False)
                                    oDoc.Contenu = oArc.zContenu.GetValeur()
                                    oDoc.Enregistrer()
                                    oDoc = Nothing
                                    OuvrirFichier(oArc.CheminFichier)
                                    If oProjet.ColHisto.Contains(oArc.CheminFichier) Then DocumentCourant.Historique = oProjet.ColHisto(oArc.CheminFichier)
                                End If
                            End If
                        End If
                    End If
                Next
                ToolStripProgressBar1.Visible = False
            Else
                oProjet.ColArchives.Clear()
            End If
            Me.Cursor = Cursors.Default
            'Mise à jour des statistiques
            AfficherStatistiquesGlobales()
            If Not Me.DocumentCourant Is Nothing Then Me.RichTextBox1.Visible = True
            'Exécution de la macro Autorun s'il y en a une
            For Each oMacro As ClassMacro In oProjet.ColCode
                If Commun.TestRegex(oMacro.Titre, "Autorun") Then
                    oMacro.Execute()
                    Exit For
                End If
            Next
        End If
    End Sub

    Public Sub SaveProjet(ByRef oProjet As ClassProjet)
        'Récupérer les fichiers ouverts et les historiques
        Me.Cursor = Cursors.WaitCursor
        oProjet.ColHisto.Clear()
        oProjet.ColArchives.Clear()
        For Each oItem As ListViewItem In Me.ListViewFichiers.Items
            Dim oDoc As ClassDocument = oItem.Tag
            'BUG: Les archives ne fonctionnent pas pour les nouveaux fichiers non-enregistrés...
            'If oDoc.Chemin <> "" Then
            Dim oArc As New ClassArchive
            oArc.CheminFichier = oDoc.Chemin
            oArc.TitreFichier = oDoc.Titre
            oArc.zContenu.SetValeur(oDoc.Contenu)
            oProjet.ColArchives.add(oArc)
            oArc = Nothing
            oProjet.ColHisto.add(oDoc.Chemin, oDoc.Historique)
            'End If
        Next
        'Récupérer les marqueurs
        oProjet.ColMarqueurs.Clear()
        For Each oItem As ListViewItem In ListViewMarqueurs.Items
            Dim oMarqueur As ClassMarqueur = oItem.Tag
            oMarqueur.Actif = oItem.Checked
            oProjet.ColMarqueurs.add(oMarqueur)
        Next
        'Récupérer les transformations
        ProjetCourant.ColTextTransform = FormTransform.ColTextTransform
        'Récupérer les transformations scriptées
        oProjet.ColFiltreScripts = FormFiltreScript.oColScripts
        'Récupérer les fragments
        oProjet.ColFragments = FormFragment.oColFragments
        'Récupérer les commandes système
        'Enregistrer le projet lui-même
        Try
            Commun.SaveXML(oProjet, oProjet.Chemin)
        Catch ex As Exception
            MsgBox("Erreur à l'enregistrement du projet: " & ex.Message)
            Exit Sub
        End Try
        Me.Cursor = Cursors.Default
    End Sub


#End Region

#Region "Outils"

    Public Sub Separation(ByVal TousDoc As Boolean, ByVal Regex As String, ByVal ModeleContenu As String, MOdeleNom As String)
        'Récupérer le contenu du document courant
        If Not DocumentCourant Is Nothing Then DocumentCourant.Contenu = Me.RichTextBox1.Text
        'Preparer la collection des documents à traiter
        Dim ColDocs As New Collection
        If TousDoc Then
            'Tous les documents
            For Each oItem As ListViewItem In ListViewFichiers.Items
                ColDocs.Add(oItem.Tag)
            Next
        Else
            'Document courant seulement
            ColDocs.Add(DocumentCourant)
        End If
        'Préparer la collection des expressions régulières a utiliser
        Dim ColExpr As New Collection
        If Regex <> "" Then
            'Utiliser l'expression définie
            Dim oOption As RegexOptions = RegexOptions.Multiline Or RegexOptions.IgnoreCase
            Dim oRegEx As New Regex(FormSeparation.TextBoxRegex.Text, oOption)
            ColExpr.Add(oRegEx)
        Else
            'Utiliser les marqueurs
            For Each oItem As ListViewItem In ListViewMarqueurs.CheckedItems
                Dim oMarqueur As ClassMarqueur = oItem.Tag
                Dim oOption As RegexOptions = RegexOptions.Multiline
                If oMarqueur.SensibleCasse = Boolean.FalseString Then oOption = oOption Or RegexOptions.IgnoreCase
                Dim oRegEx As New Regex(oMarqueur.Masque, oOption)
                ColExpr.Add(oRegEx)
            Next
        End If
        'Affichage
        Me.TabControl1.SelectedTab = Me.TabPageEdition
        Me.RichTextBox1.Visible = False
        Me.ToolStripProgressBar1.Maximum = ColDocs.Count + 1
        Me.ToolStripProgressBar1.Value = 1
        Me.ToolStripProgressBar1.Visible = True
        'Boucler sur tous les documents 
        Dim iIndex As Long = 0
        For Each oDoc As ClassDocument In ColDocs
            Me.ToolStripProgressBar1.Value += 1
            'On traite toutes les expressions
            For Each oRegex As Regex In ColExpr
                For Each oMatch As Match In oRegex.Matches(oDoc.Contenu)
                    iIndex += 1
                    Dim sContenu As String = MOdeleContenu
                    Dim sNom As String = ModeleNOm
                    If Not System.Text.RegularExpressions.Regex.IsMatch(sNom, "\$No|\$\d+") Then sNom = sNom.Replace(".", "_" & iIndex.ToString("0") & ".")
                    sContenu = System.Text.RegularExpressions.Regex.Replace(sContenu, "\$No", iIndex.ToString("0"), RegexOptions.IgnoreCase)
                    sContenu = System.Text.RegularExpressions.Regex.Replace(sContenu, "\$Nom", oDoc.Titre, RegexOptions.IgnoreCase)
                    sContenu = System.Text.RegularExpressions.Regex.Replace(sContenu, "\$Chemin", oDoc.Chemin, RegexOptions.IgnoreCase)
                    sContenu = System.Text.RegularExpressions.Regex.Replace(sContenu, "\$Dossier", My.Computer.FileSystem.GetParentPath(oDoc.Chemin), RegexOptions.IgnoreCase)
                    sNom = System.Text.RegularExpressions.Regex.Replace(sNom, "\$No", iIndex.ToString("0"), RegexOptions.IgnoreCase)
                    sNom = System.Text.RegularExpressions.Regex.Replace(sNom, "\$Nom", oDoc.Titre, RegexOptions.IgnoreCase)
                    sNom = System.Text.RegularExpressions.Regex.Replace(sNom, "\$Chemin", oDoc.Chemin, RegexOptions.IgnoreCase)
                    sNom = System.Text.RegularExpressions.Regex.Replace(sNom, "\$Dossier", My.Computer.FileSystem.GetParentPath(oDoc.Chemin), RegexOptions.IgnoreCase)
                    For iSubMatch As Integer = 0 To oMatch.Groups.Count - 1
                        sContenu = sContenu.Replace("$" & iSubMatch.ToString("0"), oMatch.Groups(iSubMatch).Value)
                        sNom = sNom.Replace("$" & iSubMatch.ToString("0"), oMatch.Groups(iSubMatch).Value)
                    Next
                    Call CreerFichierExtraction(sNom, sContenu)
                Next 'Match
            Next 'Regex
        Next 'Doc
        Me.ToolStripProgressBar1.Visible = False
        Call Me.UpdateCompteurs()
        Call Me.UpdateStatus()
        Me.RichTextBox1.Visible = True
        AjouterHistoriqueMacro("scpEdit.Separation " & TousDoc.ToString & "," & Chr(34) & Regex & Chr(34) & "," & Chr(34) & MOdeleContenu & Chr(34) & "," & Chr(34) & ModeleNOm & Chr(34))
    End Sub

    Private Sub SeparationInteractif()
        If Not DocumentCourant Is Nothing Then
            If FormSeparation.ShowDialog() = Windows.Forms.DialogResult.OK Then
                If FormSeparation.RadioButtonRegEx.Checked Then
                    Call Separation(FormSeparation.RadioButtonTousDocuments.Checked, FormSeparation.TextBoxRegex.Text, FormSeparation.TextBox1.Text, FormSeparation.RichTextBox1.Text)
                Else
                    Call Separation(FormSeparation.RadioButtonTousDocuments.Checked, "", FormSeparation.TextBox1.Text, FormSeparation.RichTextBox1.Text)
                End If
            End If
            Else
                MsgBox("Vous devez d'abord ouvrir un document!", MsgBoxStyle.Exclamation)
            End If
    End Sub

    Private Sub CreerFichierExtraction(ByVal sNom As String, ByVal sContenu As String)
        sNom = Trim(sNom)
        sNom = Regex.Replace(sNom, "[\t\n\r]", "")
        sNom = sNom.ToLower
        If System.IO.File.Exists(sNom) Then
            If MsgBox("Remplacer le fichier " & sNom & " déjà présent ?", MsgBoxStyle.Question Or MsgBoxStyle.YesNo) = MsgBoxResult.No Then Exit Sub
        End If
        Dim oNewDocument As New ClassDocument("", False)
        oNewDocument.Contenu = sContenu
        oNewDocument.EnregistrerSous(sNom)
        Dim oNewItem As ListViewItem = Me.ListViewFichiers.Items(sNom)
        If oNewItem Is Nothing Then
            oNewItem = Me.ListViewFichiers.Items.Add(oNewDocument.Chemin, oNewDocument.Titre, oNewDocument.GetIconeName())
            oNewItem.SubItems.Add("")
        End If
        oNewItem.Tag = oNewDocument
        oNewDocument.oItem = oNewItem
        oNewItem.Selected = True
        Dim sDossier As String = System.IO.Path.GetDirectoryName(sNom)
        Dim oGroupe As ListViewGroup = ListViewFichiers.Groups(sDossier)
        If oGroupe Is Nothing Then oGroupe = ListViewFichiers.Groups.Add(sDossier, sDossier)
        oNewItem.Group = oGroupe
        oNewItem.EnsureVisible()
        AfficheCourant(oNewItem)
        RechercherMarqeursDocCourant()
        Me.TabControl1.SelectedTab = Me.TabPageEdition
    End Sub

    Private Sub Fusion()
        'Afficher le dialogue des options
        If Not DocumentCourant Is Nothing Then
            DocumentCourant.Contenu = Me.RichTextBox1.Text
            If FormFusion.ShowDialog() = Windows.Forms.DialogResult.OK Then
                DocumentCourant.Contenu = Me.RichTextBox1.Text
                'Affichage
                Me.TabControl1.SelectedTab = Me.TabPageEdition
                Me.RichTextBox1.Visible = False
                If FormFusion.RadioButtonCourant.Checked Then
                    Me.ToolStripProgressBar1.Maximum = 2
                Else
                    Me.ToolStripProgressBar1.Maximum = Me.ListViewFichiers.Items.Count + 1
                End If
                Me.ToolStripProgressBar1.Value = 1
                Me.ToolStripProgressBar1.Visible = True
                'Preparer le rapport
                Dim sResultGlobal As String = FormFusion.Fusionner()
                Me.ToolStripProgressBar1.Visible = False
                'Création du nouveau document
                Call Me.Nouveau()
                Me.RichTextBox1.Visible = False
                Me.RichTextBox1.Text = sResultGlobal
                Me.DocumentCourant.Contenu = sResultGlobal
                Call RechercherMarqeursDocCourant()
                Call Me.UpdateCompteurs()
                Call Me.UpdateStatus()
                Me.RichTextBox1.Visible = True
                Dim sCommande As String = "scpEdit.Fusion "
                sCommande &= FormFusion.RadioButtonTousDocuments.Checked.ToString
                If FormFusion.RadioButtonRegEx.Checked Then
                    sCommande &= "," & Chr(34) & FormFusion.TextBoxRegEx.Text & Chr(34)
                Else
                    sCommande &= "," & Chr(34) & Chr(34)
                End If
                If FormFusion.RadioButtonMatchs.Checked Then sCommande &= ",1"
                If FormFusion.RadioButtonSubMatchLignes.Checked Then sCommande &= ",2"
                If FormFusion.RadioButtonSubMatchCol.Checked Then sCommande &= ",3"
                If FormFusion.RadioButtonModele.Checked Then sCommande &= ",4"
                sCommande &= "," & FormFusion.CheckBoxTrier.Checked.ToString
                sCommande &= "," & FormFusion.CheckBoxDoublons.Checked.ToString
                sCommande &= "," & FormFusion.CheckBoxGrouper.Checked.ToString
                sCommande &= "," & FormFusion.CheckBoxStat.Checked.ToString
                If FormFusion.RadioButtonRegEx.Checked Then sCommande &= "," & Chr(34) & FormFusion.RichTextBox1.Text & Chr(34)
                AjouterHistoriqueMacro(sCommande)
            End If
        Else
            MsgBox("Vous devez d'abord ouvrir un document!", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Public Sub ReformaterXML()
        Dim Doc As New System.Xml.XmlDocument()
        Try
            Doc.LoadXml(Me.RichTextBox1.Text)
            Dim oMemStrm As New System.IO.MemoryStream()
            Dim oXmlWriter As New System.Xml.XmlTextWriter(oMemStrm, System.Text.Encoding.UTF8)
            oXmlWriter.Formatting = Xml.Formatting.Indented
            oXmlWriter.Indentation = 4
            oXmlWriter.IndentChar = " "
            Doc.Save(oXmlWriter)
            'oXmlWriter.Flush()
            Dim sXML As String = System.Text.Encoding.UTF8.GetString(oMemStrm.GetBuffer())
            If Asc(sXML(0)) = 63 Then sXML = sXML.Remove(0, 1)
            Me.RichTextBox1.Visible = False
            Me.RichTextBox1.Text = sXML
            RechercherMarqeursDocCourant()
            Me.RichTextBox1.Visible = True
            AjouterHistoriqueMacro("scpEdit.ReformaterXML()")
        Catch Ex As Exception
            MsgBox("Reformatage xml impossible: " & Ex.Message)
        End Try
    End Sub


#End Region

#Region "Recherche"
    Private Sub ChercherSuivant()
        If Not DocumentCourant Is Nothing Then
            'On enregistre le point de départ
            Dim iPos As Integer = Me.RichTextBox1.SelectionStart
            If Me.RichTextBox1.SelectionLength > 0 Then iPos += Me.RichTextBox1.SelectionLength
            Dim iPosTrouve As Integer = Me.RichTextBox1.Text.Length + 1
            Dim iLenghtTrouve As Integer = 0
            Dim Options As RegexOptions = RegexOptions.Multiline Or RegexOptions.IgnoreCase
            For Each oMatch As Match In Regex.Matches(Me.RichTextBox1.Text, Me.ToolStripTextBoxRec.Text, Options)
                If (oMatch.Index >= iPos) And (oMatch.Index < iPosTrouve) Then
                    iPosTrouve = oMatch.Index
                    iLenghtTrouve = oMatch.Length
                    Exit For
                End If
            Next
            If iPosTrouve = Me.RichTextBox1.Text.Length + 1 Then
                'On a rien trouvé, on passe au document suivant
                Dim iIndex As Integer = Me.ListViewFichiers.SelectedIndices(0) + 1
                If iIndex >= Me.ListViewFichiers.Items.Count Then iIndex = 0
                Me.ListViewFichiers.Items(iIndex).Selected = True
                AfficheCourant(Me.ListViewFichiers.SelectedItems(0))
                Me.RichTextBox1.SelectionStart = 0
                Me.RichTextBox1.SelectionLength = 0
                If (iIndex = Me.ChercherSuivantIndex) Then
                    MsgBox("Expression " & Chr(34) & Me.ToolStripTextBoxRec.Text & Chr(34) & " introuvable!", MsgBoxStyle.Information)
                Else
                    Call ChercherSuivant()
                End If
            Else
                'On affiche la trouvaille
                Me.RichTextBox1.SelectionStart = iPosTrouve
                Me.RichTextBox1.SelectionLength = iLenghtTrouve
                Me.RichTextBox1.Focus()
                Me.TabControl1.SelectedTab = Me.TabPageEdition
            End If
        Else
            MsgBox("Vous devez d'abord ouvrir un document!", MsgBoxStyle.Exclamation)
        End If
    End Sub

#End Region

#Region "Stats"

    Public Sub AfficherStatistiquesGlobales()
        Me.ListViewStatGlobales.Clear()
        'Entete
        Me.ListViewStatGlobales.Columns.Add("Fichier")
        For Each oItemMarqueur As ListViewItem In Me.ListViewMarqueurs.CheckedItems
            Me.ListViewStatGlobales.Columns.Add(oItemMarqueur.Text)
        Next
        Dim iGrandTotal As Integer = 0
        Me.ListViewStatGlobales.Columns.Add("Total")
        'Fichiers
        For Each oItemFichier As ListViewItem In Me.ListViewFichiers.Items
            Dim oDoc As ClassDocument = oItemFichier.Tag
            Dim oNewItemStat As ListViewItem = Me.ListViewStatGlobales.Items.Add(oDoc.Chemin, oDoc.Titre, "Fichier")
            oNewItemStat.UseItemStyleForSubItems = False
            Dim iTotal As Integer = 0
            For Each oItemMarqueur As ListViewItem In Me.ListViewMarqueurs.CheckedItems
                Dim oSubItem As ListViewItem.ListViewSubItem
                Dim oMarqueur As ClassMarqueur
                If oDoc.Stats.ContainsKey(oItemMarqueur.Text) Then
                    oSubItem = oNewItemStat.SubItems.Add(oDoc.Stats(oItemMarqueur.Text).ToString("0"))
                    iTotal += oDoc.Stats(oItemMarqueur.Text)
                Else
                    oSubItem = oNewItemStat.SubItems.Add("0")
                End If
                oMarqueur = oItemMarqueur.Tag
                oSubItem.BackColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulFondPrimaire)
                oSubItem.ForeColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulTextePrimaire)
            Next
            oNewItemStat.SubItems.Add(iTotal.ToString("0"))
            iGrandTotal += iTotal
        Next
        'Totaux
        Dim oNewItemTotaux As ListViewItem = Me.ListViewStatGlobales.Items.Add("Totaux", "Totaux", "")
        oNewItemTotaux.UseItemStyleForSubItems = False
        For Each oItemMarqueur As ListViewItem In Me.ListViewMarqueurs.CheckedItems
            Dim oMarqueur As ClassMarqueur = oItemMarqueur.Tag
            Dim oSubItem As ListViewItem.ListViewSubItem = oNewItemTotaux.SubItems.Add(oMarqueur.Compteur)
            oSubItem.BackColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulFondPrimaire)
            oSubItem.ForeColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulTextePrimaire)
        Next
        oNewItemTotaux.SubItems.Add(iGrandTotal.ToString("0"))
        'Ajuster les largeurs de colonnes
        For Each oCol As ColumnHeader In Me.ListViewStatGlobales.Columns
            If oCol.Text = "Fichier" Then
                oCol.AutoResize(ColumnHeaderAutoResizeStyle.ColumnContent)
            Else
                oCol.AutoResize(ColumnHeaderAutoResizeStyle.HeaderSize)
            End If
        Next
    End Sub

    Public Function ExporterStatistiquesGlobales() As String
        Dim sStats As String = ""
        'Entete
        For Each oCol As ColumnHeader In Me.ListViewStatGlobales.Columns
            sStats &= oCol.Text & vbTab
        Next
        sStats &= vbCrLf
        'Lignes
        For Each oItem As ListViewItem In Me.ListViewStatGlobales.Items
            For Each oSubItem As ListViewItem.ListViewSubItem In oItem.SubItems
                sStats &= oSubItem.Text & vbTab
            Next
            sStats &= vbCrLf
        Next
        Return sStats
    End Function

#End Region

    Private Sub RechergerLaDernièreVersionHistoriqueDisponibleToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RechergerLaDernièreVersionHistoriqueDisponibleToolStripMenuItem.Click
        Call RetourCourant()
    End Sub

    Private Sub CopierLeNomDuFichierCourantToolStripMenuItem_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopierLeNomDuFichierCourantToolStripMenuItem.Click
        CopierNomCourant()
    End Sub

    Private Sub ConserverLesVersionsHistoriquesmax6ToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        My.Settings.ConserverHistorique = ConserverLesVersionsHistoriquesmax6ToolStripMenuItem.Checked
    End Sub

    Private Sub AnnulerToutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AnnulerToutToolStripMenuItem.Click
        UndoAll()
    End Sub

    Private Sub SupprimerLesVersionsEnHistoriqueToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerLesVersionsEnHistoriqueToolStripMenuItem.Click
        Call SupprimerHistoriques()
    End Sub

    Public Sub SupprimerHistoriques()
        If MsgBox("Purger le projet des versions historiques de tous les documents ouverts?", MsgBoxStyle.Question Or MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
            For Each oItem As ListViewItem In Me.ListViewFichiers.Items
                Dim oDoc As ClassDocument = oItem.Tag
                oDoc.Historique.Vider()
            Next
            AfficherProprietes()
        End If
    End Sub

    Private Sub RetourÀUneVersionAntérieureToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RetourÀUneVersionAntérieureToolStripMenuItem.Click
        Call RetourCourant()
    End Sub

    Private Sub TexteValidéParUnMarqueurToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TexteValidéParUnMarqueurToolStripMenuItem.Click
        Call InsererTexteMarqueur()
    End Sub

    Public Sub InsererTexteMarqueur()
        If FormInsererTexteMarqueur.ShowDialog() = Windows.Forms.DialogResult.OK Then
            Me.RichTextBox1.SelectedRtf = FormInsererTexteMarqueur.RichTextBox1.Rtf
        End If
    End Sub

    Private Sub TexteValidéParUnMarqueurToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TexteValidéParUnMarqueurToolStripMenuItem1.Click
        Call InsererTexteMarqueur()
    End Sub

    Private Sub InsérerUnTexteValidéParMarqueurToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InsérerUnTexteValidéParMarqueurToolStripMenuItem.Click
        Call InsererTexteMarqueur()
    End Sub

    Public Sub SupprimerMarqueCourant()
        Dim oMarqueur As ClassMarqueur
        For Each oItem As ListViewItem In Me.ListViewMarqueurs.Items
            oMarqueur = oItem.Tag
            RichTextBox1.Text = System.Text.RegularExpressions.Regex.Replace(RichTextBox1.Text, oMarqueur.Masque, "", RegexOptions.IgnoreCase)
        Next
        Call Me.RechercherMarqeursDocCourant()
        AjouterHistoriqueMacro("scpEdit.SupprimerTexteMarque()")
    End Sub

    Private Sub SupprimerMarqueTous()
        If MsgBox("Supprimer le texte marqué de tous les documents ouverts?", MsgBoxStyle.Question Or MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
            Dim oOldItem = oItemCourant
            Me.Cursor = Cursors.WaitCursor
            Me.RichTextBox1.Visible = False
            Me.RichTextBox1.SuspendLayout()
            Me.iChaineTrouvee = 0
            Me.ToolStripProgressBar1.Maximum = Me.ListViewFichiers.Items.Count + 1
            Me.ToolStripProgressBar1.Minimum = 0
            Me.ToolStripProgressBar1.Value = 0
            Me.ToolStripProgressBar1.Visible = True
            'Faire les suppressions
            For Each oItem As ListViewItem In Me.ListViewFichiers.Items
                Me.AfficheCourant(oItem)
                Call SupprimerMarqueCourant()
                Me.ToolStripProgressBar1.Value += 1
                My.Application.DoEvents()
            Next
            'Statistiques
            AfficherStatistiquesGlobales()
            'Reactualiser l'affichage
            Me.ToolStripProgressBar1.Visible = False
            Me.RichTextBox1.ResumeLayout()
            Me.AfficheCourant(oOldItem)
            If Not DocumentCourant Is Nothing Then RichTextBox1.Visible = True
            Me.Cursor = Cursors.Default
        End If
    End Sub

    Private Sub SupprimerLeTexteMarquéDuDocumentCourantToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerLeTexteMarquéDuDocumentCourantToolStripMenuItem1.Click
        Call SupprimerMarqueCourant()
    End Sub

    Private Sub SupprimerLeTexteMarquéDeTousLesDocumentsToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerLeTexteMarquéDeTousLesDocumentsToolStripMenuItem1.Click
        Call SupprimerMarqueTous()
    End Sub

    Private Sub DésactiverTousToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DésactiverTousToolStripMenuItem.Click
        Call DesactiverMarqueurs()
    End Sub

    Private Sub DesactiverMarqueurs()
        For Each oItem As ListViewItem In Me.ListViewMarqueurs.Items
            oItem.Checked = False
        Next
        Call RechercherMarqueurs()
    End Sub

    Private Sub ActiverMarqueurs()
        For Each oItem As ListViewItem In Me.ListViewMarqueurs.Items
            oItem.Checked = True
        Next
        Call RechercherMarqueurs()
    End Sub

    Private Sub ActiverTousToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ActiverTousToolStripMenuItem.Click
        Call ActiverMarqueurs()
    End Sub


    Private Sub ExtraireLesExpressionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExtraireLesExpressionToolStripMenuItem.Click
        Call ExtraireMasques()
    End Sub

    Public Sub ExtraireMasques()
        AjouterHistoriqueMacro("scpEdit.InsererMasques()")
        If Me.ListViewMarqueurs.CheckedItems.Count > 0 Then
            Me.Nouveau()
            Dim oMarqueur As ClassMarqueur
            For Each oItem As ListViewItem In Me.ListViewMarqueurs.CheckedItems
                oMarqueur = oItem.Tag
                Me.RichTextBox1.SelectedText = oMarqueur.Titre & vbCrLf
                Me.RichTextBox1.SelectedText = "  " & oMarqueur.Masque & vbCrLf
            Next
        Else
            MsgBox("Il n'y a aucun marqueur actif", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub ExtraireLesExpressionsRégulièresToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExtraireLesExpressionsRégulièresToolStripMenuItem.Click
        Call ExtraireMasques()
    End Sub


    Private Sub ImporterLesMarqueursDunProjetToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImporterLesMarqueursDunProjetToolStripMenuItem.Click
        Call ImporterMarqueurs()
    End Sub

    Private Sub ImporterMarqueurs()
        Me.OpenFileDialog1.Filter = "Projet scpEdit|*.scp"
        Me.OpenFileDialog1.DefaultExt = ".scp"
        Me.OpenFileDialog1.Title = "Importer les marqueurs d'un projet..."
        Me.OpenFileDialog1.Multiselect = False
        If My.Settings.DossierProjets <> "" Then
            If My.Computer.FileSystem.DirectoryExists(My.Settings.DossierProjets) Then Me.OpenFileDialog1.InitialDirectory = My.Settings.DossierProjets
        End If
        'On ne veut pas le nom par défaut...
        Me.OpenFileDialog1.FileName = ""
        If Me.OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            ImporterMarqueursProjet(Me.OpenFileDialog1.FileName)
            AjouterHistoriqueMacro("scpEdit.ImporterMarqueurs(" & Chr(34) & Me.OpenFileDialog1.FileName & Chr(34) & ")")
        End If
    End Sub

    Public Sub ImporterMarqueursProjet(ByVal Chemin As String)
        Dim oProjetImport As New ClassProjet
        oProjetImport.Chemin = Me.OpenFileDialog1.FileName
        'Lire le projet lui-même
        If My.Computer.FileSystem.FileExists(Chemin) Then
            Me.Cursor = Cursors.WaitCursor
            Try
                Commun.LoadXML(oProjetImport, Chemin)
            Catch ex As Exception
                Me.Cursor = Cursors.Default
                MsgBox("Erreur à la lecture du projet: " & ex.Message)
                Exit Sub
            End Try
            'Affichage des marqueurs
            ListViewMarqueurs.SuspendLayout()
            For Each oMarqueur As ClassMarqueur In oProjetImport.ColMarqueurs
                oMarqueur.ResetCompteur()
                oMarqueur.Actif = False
                If Me.ListViewMarqueurs.Items.ContainsKey(oMarqueur.Titre) Then
                    Dim No As Integer = 2
                    While Me.ListViewMarqueurs.Items.ContainsKey(oMarqueur.Titre & No)
                        No += 1
                    End While
                    oMarqueur.Titre &= No
                End If
                Dim oItem As ListViewItem = ListViewMarqueurs.Items.Add(oMarqueur.Titre, oMarqueur.Titre, "")
                oItem.SubItems.Add("")
                oItem.Checked = oMarqueur.Actif
                oItem.ToolTipText = oMarqueur.Masque
                oItem.Tag = oMarqueur
                oItem.BackColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulFondPrimaire)
                oItem.ForeColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulTextePrimaire)
                'oItem.SubItems(0).BackColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulFondSecondaire)
                'oItem.SubItems(0).ForeColor = System.Drawing.ColorTranslator.FromHtml(oMarqueur.CoulTexteSecondaire)
            Next
            ListViewMarqueurs.ResumeLayout()
            oProjetImport = Nothing
            Me.Cursor = Cursors.Default
        End If
    End Sub

    Private Sub ImporterLesMarqueursDunProjetToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ImporterLesMarqueursDunProjetToolStripMenuItem1.Click
        Call ImporterMarqueurs()
    End Sub


    Private Sub ExécuterLaLigneCouranteCommeUneCommandeToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExécuterLaLigneCouranteCommeUneCommandeToolStripMenuItem1.Click
        Call InsererShell()
    End Sub

    Private Sub OrdinateursDuDomaineToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OrdinateursDuDomaineToolStripMenuItem.Click
        Call InsererOrdinateursDomaine()
    End Sub

    Public Function GetInfoAD(ByVal sFiltre As String, ByVal sDomaine As String, ByVal sUserName As String, ByVal sPassword As String)
        Me.ToolStripProgressBar1.Maximum = 100
        Me.ToolStripProgressBar1.Value = 1
        Me.ToolStripProgressBar1.Visible = True
        My.Application.DoEvents()
        Dim sListe As String = ""
        Dim oResultCol As System.DirectoryServices.SearchResultCollection
        Dim sProp() As String
        Dim sValue As String
        Me.DirectorySearcher1.Filter = sFiltre
        Me.DirectorySearcher1.PageSize = 1000
        Dim oContext As System.DirectoryServices.ActiveDirectory.DirectoryContext
        Dim oDomain As System.DirectoryServices.ActiveDirectory.Domain
        If sUserName <> "" Then
            oContext = New System.DirectoryServices.ActiveDirectory.DirectoryContext(System.DirectoryServices.ActiveDirectory.DirectoryContextType.Domain, sDomaine, sUserName, sPassword)
        Else
            oContext = New System.DirectoryServices.ActiveDirectory.DirectoryContext(System.DirectoryServices.ActiveDirectory.DirectoryContextType.Domain, sDomaine)
        End If
        oDomain = System.DirectoryServices.ActiveDirectory.Domain.GetDomain(oContext)
        Me.DirectorySearcher1.SearchRoot = oDomain.GetDirectoryEntry()
        My.Application.DoEvents()
        Try
            oResultCol = Me.DirectorySearcher1.FindAll()
            Me.RichTextBox1.Cursor = Cursors.WaitCursor
            Me.ToolStripProgressBar1.Maximum = oResultCol.Count + 1
            sProp = FormConnect.ComboBoxProp.Text.Split(",")
            For Each oResult As System.DirectoryServices.SearchResult In oResultCol
                sValue = ""
                For Each sPropName As String In sProp
                    If sValue <> "" Then sValue &= ","
                    Try
                        sValue &= oResult.Properties(sPropName).Item(0).ToString
                    Catch ex As Exception
                        sValue &= "!" & sPropName & " inconnu"
                    End Try
                Next
                sListe &= sValue & vbCrLf
                Me.ToolStripProgressBar1.Value += 1
                My.Application.DoEvents()
            Next
        Catch Ex As Exception
            sListe &= vbCrLf & "Erreur d'accès à Active Directory:" & Ex.Message & vbCrLf
        End Try
        Me.RichTextBox1.Cursor = Cursors.Default
        Me.ToolStripProgressBar1.Visible = False
        Return sListe
    End Function

    Private Sub InsererRechercheAD(ByVal sFiltre As String)
        If DocumentCourant Is Nothing Then Call Me.Nouveau()
        FormConnect.ComboBoxFiltre.Text = sFiltre
        FormConnect.ComboBoxFiltre.Enabled = True
        If FormConnect.ShowDialog() = MsgBoxResult.Ok Then
            If FormConnect.CheckBoxUser.Checked Then
                Me.RichTextBox1.SelectedText = Me.GetInfoAD(FormConnect.ComboBoxFiltre.Text, FormConnect.ComboBoxDomaine.Text, FormConnect.TextBoxUserName.Text, FormConnect.TextBoxPassword.Text)
                Dim sCommande As String = "scpEdit.InsererTexte(scpEdit.GetInfoAD("
                sCommande &= Chr(34) & FormConnect.ComboBoxFiltre.Text & Chr(34) & ","
                sCommande &= Chr(34) & FormConnect.ComboBoxDomaine.Text & Chr(34) & ","
                sCommande &= Chr(34) & FormConnect.TextBoxUserName.Text & Chr(34) & ","
                sCommande &= Chr(34) & FormConnect.TextBoxPassword.Text & Chr(34) & "))"
                AjouterHistoriqueMacro(sCommande)
            Else
                Me.RichTextBox1.SelectedText = Me.GetInfoAD(sFiltre, FormConnect.ComboBoxDomaine.Text, "", "")
                Dim sCommande As String = "scpEdit.InsererTexte(scpEdit.GetInfoAD("
                sCommande &= Chr(34) & FormConnect.ComboBoxFiltre.Text & Chr(34) & ","
                sCommande &= Chr(34) & FormConnect.ComboBoxDomaine.Text & Chr(34) & ","
                sCommande &= Chr(34) & Chr(34) & ","
                sCommande &= Chr(34) & Chr(34) & "))"
                AjouterHistoriqueMacro(sCommande)
            End If
        End If
    End Sub

    Private Sub InsererOrdinateursDomaine()
        InsererRechercheAD("(objectCategory=computer)")
    End Sub

    Private Sub SupprimerLeTexteMarquéDuDocumentCourantToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerLeTexteMarquéDuDocumentCourantToolStripMenuItem.Click
        Call SupprimerMarqueCourant()
        Call AfficherStatistiquesGlobales()
    End Sub

    Private Sub SupprimerLeTexteMarquéDeTousLesDocumentsToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerLeTexteMarquéDeTousLesDocumentsToolStripMenuItem.Click
        Call SupprimerMarqueTous()
    End Sub

    Friend Function GetDefaultCoul(ByVal Courante As String) As String
        'Construire une collection de couleurs disponibles
        Dim oList As String() = {"#FFFF00", "#FF0000", "#00FF00", "#00FFFF", "#0080C0", "#C0C0C0", "#808080", "#FF00FF", "#8080FF", "#FF8040", "#78BCBC", "#B9B900", "#BB7777", "#6FFF6F"}
        Dim oColCoul As New System.Collections.Specialized.StringCollection
        Dim noCoul As Integer = 0
        For Each sCoul As String In oList
            oColCoul.Add(sCoul)
        Next
        'Retirer les couleurs déjà prises par des marqueurs
        Dim oMarqueur As ClassMarqueur
        For Each oItem As ListViewItem In Me.ListViewMarqueurs.Items
            oMarqueur = oItem.Tag
            If oColCoul.Contains(oMarqueur.CoulFondPrimaire) Then oColCoul.Remove(oMarqueur.CoulFondPrimaire)
        Next     
        'Si il n'y a plus de couleurs libres, on a pas le choix de piger dans la liste complete
        If oColCoul.Count = 0 Then
            For Each sCoul As String In oList
                oColCoul.Add(sCoul)
            Next
            'Dans ce cas, on ne veut pas toujours utiliser la première car on veut répartir également
            If Courante = "" Then Courante = oColCoul.Item(Me.ListViewMarqueurs.Items.Count + 1 Mod oColCoul.Count)
        End If
        If Courante = "" Then Courante = oColCoul.Item(0)
        'On prend la couleur qui suit la courante
        noCoul = oColCoul.IndexOf(Courante) + 1
        If noCoul >= oColCoul.Count Then noCoul = 0
        Return oColCoul.Item(noCoul)
    End Function

    Friend Function GetCoulComp(ByVal CoulPrim As String) As String
        Dim oCoul As Color = System.Drawing.ColorTranslator.FromHtml(CoulPrim)
        oCoul = ControlPaint.LightLight(oCoul)
        Return System.Drawing.ColorTranslator.ToHtml(oCoul)
        'Dim oListPrim As String() = {"#FFFF80", "#FF8080", "#80FF80", "#80FFFF", "#ACCBFF", "#E5E5E5", "#ACACAC", "#FF80C0", "#CCCCFF", "#FFC6AA", "#D9ECEC", "#DFDF00", "#E1C4C4", "#BBFFBB"}
        'Dim oListComp As String() = {"#FFFF00", "#FF0000", "#00FF00", "#00FFFF", "#0080C0", "#C0C0C0", "#808080", "#FF00FF", "#8080FF", "#FF8040", "#78BCBC", "#B9B900", "#BB7777", "#6FFF6F"}
        'For i As Integer = oListPrim.GetLowerBound(0) To oListPrim.GetUpperBound(0)
        'If oListPrim(i) = CoulPrim Then Return oListComp(i)
        'Next
        'Defaut
        'Return CoulPrim
    End Function


    Private Sub ExécuterLeTexteSélecionnéEnTantQueMacroVBScriptToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExécuterLeTexteSélecionnéEnTantQueMacroVBScriptToolStripMenuItem.Click
        Call Me.InsererCode()
    End Sub

    Private Sub ExécuterLigneCouranteAvecPowerShellToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExécuterLigneCouranteAvecPowerShellToolStripMenuItem.Click
        Call Me.InsererPowerShell()
    End Sub

    Private Sub ToolStripButtonCommandRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonCommandRun.Click
        Call Me.CodeRun()
    End Sub

    Private Sub ToolStripButtonCommandEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonCommandEdit.Click
        Call Me.CodeEdit()
    End Sub

    Private Sub CodeEdit()
        'Sélection du code existant si disponible
        Dim oCode As ClassMacro = Nothing
        If ProjetCourant.ColCode.Contains(Me.ToolStripComboBoxCommand.Text) Then
            'On modifie une macro déjà enregistrée
            oCode = ProjetCourant.ColCode.Item(Me.ToolStripComboBoxCommand.Text)
            If oCode.Edit Then
                If oCode.Titre <> Me.ToolStripComboBoxCommand.Text Then
                    ToolStripComboBoxCommand.Items.Remove(Me.ToolStripComboBoxCommand.Text)
                    ToolStripComboBoxCommand.Items.Add(oCode.Titre)
                    ToolStripComboBoxCommand.Text = oCode.Titre
                End If
            End If
        Else
            'On va créer une nouvelle macro
            oCode = New ClassMacro
            Dim No As Integer = 1
            Do While Me.ToolStripComboBoxCommand.Items.Contains("Macro" & No.ToString)
                No += 1
            Loop
            oCode.Titre = "Macro" & No.ToString
            If Me.ToolStripComboBoxCommand.Text = "" Then
                oCode.Code = "'Nouvelle macro " & vbCrLf & "scpEdit.InsererTexte (""Bonjour"")"
            Else
                oCode.Code = Me.ToolStripComboBoxCommand.Text
                oCode.Code = System.Text.RegularExpressions.Regex.Replace(oCode.Code, "(ps|power|powershell):(.+)", "scpEdit.RunPowerShell(" & Chr(34) & "$2" & Chr(34) & ")", RegexOptions.IgnoreCase)
                oCode.Code = System.Text.RegularExpressions.Regex.Replace(oCode.Code, "(cmd|shell):(.+)", "scpEdit.RunShell(" & Chr(34) & "$2" & Chr(34) & ")", RegexOptions.IgnoreCase)
                If Not System.Text.RegularExpressions.Regex.IsMatch(oCode.Code, "scpedit\.(Inserer|Ajouter)Texte|wscript\.echo") Then oCode.Code = "scpEdit.InsererTexte " & oCode.Code
            End If
            If oCode.Edit() Then
                ProjetCourant.ColCode.add(oCode.Titre, oCode)
                ToolStripComboBoxCommand.Items.Add(oCode.Titre)
                ToolStripComboBoxCommand.Text = oCode.Titre
            End If
        End If
    End Sub

    Private Sub CodeRun()
        'Sélection du code existant si disponible
        Dim oCode As ClassMacro = Nothing
        If Me.ToolStripComboBoxCommand.Text <> "" Then
            If ProjetCourant.ColCode.Contains(Me.ToolStripComboBoxCommand.Text) Then
                'On une macro enregistrée
                oCode = ProjetCourant.ColCode.Item(Me.ToolStripComboBoxCommand.Text)
            Else
                'On a du code à exécuter surle fly
                oCode = New ClassMacro
                oCode.Code = Me.ToolStripComboBoxCommand.Text
                oCode.Code = System.Text.RegularExpressions.Regex.Replace(oCode.Code, "(ps|power|powershell):(.+)", "scpEdit.RunPowerShell(" & Chr(34) & "$2" & Chr(34) & ")", RegexOptions.IgnoreCase)
                oCode.Code = System.Text.RegularExpressions.Regex.Replace(oCode.Code, "(cmd|shell):(.+)", "scpEdit.RunShell(" & Chr(34) & "$2" & Chr(34) & ")", RegexOptions.IgnoreCase)
                If Not System.Text.RegularExpressions.Regex.IsMatch(oCode.Code, "scpedit\.(Inserer|Ajouter)Texte|wscript\.echo") Then oCode.Code = "scpEdit.InsererTexte " & oCode.Code
            End If
            Dim sSortie As String = oCode.Execute()
            If DocumentCourant Is Nothing Then Call Me.Nouveau()
            Me.RichTextBox1.SelectedText = sSortie
            Me.RichTextBox1.ScrollToCaret()
        Else
            'On n'a rien à exécuter. On veut probablement éditer une nouvelle macro ?
            Call CodeEdit()
        End If
    End Sub

    Private Sub ToolStripButtonCommandDel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButtonCommandDel.Click
        Call CodeDel()
    End Sub

    Private Sub CodeDel()
        If Me.ToolStripComboBoxCommand.Text <> "" Then
            If ProjetCourant.ColCode.Contains(Me.ToolStripComboBoxCommand.Text) Then
                ProjetCourant.ColCode.Remove(Me.ToolStripComboBoxCommand.Text)
                Me.ToolStripComboBoxCommand.Items.Remove(Me.ToolStripComboBoxCommand.Text)
                Me.ToolStripComboBoxCommand.Text = ""
            End If
        End If
    End Sub

    Private Sub ToolStripComboBoxCommand_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles ToolStripComboBoxCommand.KeyDown
        If e.KeyCode = Keys.Enter Then
            e.SuppressKeyPress = True
            Call Me.CodeRun()
        End If
        If e.KeyCode = Keys.Delete Then
            e.SuppressKeyPress = True
            Call Me.CodeDel()
        End If
    End Sub

    Public Sub OuvrirFichiersSelectionAuto()
        'Version auto sans confirmation
        Const sRegexFull As String = "(([a-z]:)|(\\\\[^<>:""/\\\?\*\.\r\n]+(\\[^<>:""/\\\?\*\.\r\n]+)))(\\[^<>:""/\\\?\*\.\r\n]+)+(\.[^<>:""/\\\?\*\.\r\n\s]+)+"
        Dim oOldItem As ListViewItem = Me.oItemCourant
        Dim oOldPos As Integer = Me.RichTextBox1.SelectionStart
        Dim oOldLen As Integer = Me.RichTextBox1.SelectionLength
        Dim sArgs As String = Me.RichTextBox1.SelectedText
        'Si on n'a pas de sélection alors on se rabat sur la ligne courante
        If (sArgs = "") And (Me.RichTextBox1.TextLength > 0) Then
            'On capture la ligne courante
            Dim NoLigne As Integer = Me.RichTextBox1.GetLineFromCharIndex(Me.RichTextBox1.SelectionStart)
            sArgs = Me.RichTextBox1.Lines(NoLigne)
        End If
        FormOuvrirListe.Reset()
        'On boucle sur tous les noms de fichiers complet
        For Each oMatch As System.Text.RegularExpressions.Match In System.Text.RegularExpressions.Regex.Matches(sArgs, sRegexFull, System.Text.RegularExpressions.RegexOptions.IgnoreCase Or System.Text.RegularExpressions.RegexOptions.Multiline)
            FormOuvrirListe.AjouterFichierSiExiste(oMatch.Value)
        Next
        For Each oItem As ListViewItem In FormOuvrirListe.ListView1.CheckedItems()
            OuvrirFichier(oItem.Text)
        Next
        Me.AfficheCourant(oOldItem)
        Me.RichTextBox1.SelectionStart = oOldPos
        Me.RichTextBox1.SelectionLength = oOldLen
        'AjouteHistorique("scpEdit.OuvrirFichiersSelection()")
    End Sub

    Private Sub OuvrirFichiersSelection()
        'Version interactive avec confirmation
        Const sRegexFull As String = "(([a-z]:)|(\\\\[^<>:""/\\\?\*\.\r\n]+(\\[^<>:""/\\\?\*\.\r\n]+)))(\\[^<>:""/\\\?\*\.\r\n]+)+(\.[^<>:""/\\\?\*\.\r\n\s]+)+"
        Dim oOldItem As ListViewItem = oItemCourant
        Dim oOldPos As Integer = Me.RichTextBox1.SelectionStart
        Dim oOldLen As Integer = Me.RichTextBox1.SelectionLength
        Dim sArgs As String = Me.RichTextBox1.SelectedText
        'Si on n'a pas de sélection alors on se rabat sur la ligne courante
        If (sArgs = "") And (Me.RichTextBox1.TextLength > 0) Then
            'On capture la ligne courante
            Dim NoLigne As Integer = Me.RichTextBox1.GetLineFromCharIndex(Me.RichTextBox1.SelectionStart)
            sArgs = Me.RichTextBox1.Lines(NoLigne)
        End If
        FormOuvrirListe.Reset()
        'On boucle sur tous les noms de fichiers complet
        For Each oMatch As System.Text.RegularExpressions.Match In System.Text.RegularExpressions.Regex.Matches(sArgs, sRegexFull, RegexOptions.IgnoreCase Or RegexOptions.Multiline)
            FormOuvrirListe.AjouterFichierSiExiste(oMatch.Value)
        Next
        If FormOuvrirListe.ShowSiFichiers() = Windows.Forms.DialogResult.OK Then
            For Each oItem As ListViewItem In FormOuvrirListe.ListView1.CheckedItems()
                OuvrirFichier(oItem.Text)
            Next
        End If
        Me.AfficheCourant(oOldItem)
        Me.RichTextBox1.SelectionStart = oOldPos
        Me.RichTextBox1.SelectionLength = oOldLen
        AjouterHistoriqueMacro("scpEdit.OuvrirFichiersSelection()")
    End Sub

    Public Sub OuvrirFichiersMarqueursAuto()
        'Version auto sans confirmation interactive
        Dim oOldItem As ListViewItem = Me.oItemCourant
        Dim oOldPos As Integer = Me.RichTextBox1.SelectionStart
        Dim oOldLen As Integer = Me.RichTextBox1.SelectionLength
        Dim sArgs As String = Me.RichTextBox1.SelectedText
        'Si on n'a pas de sélection alors on se rabat sur la ligne courante
        If (sArgs = "") And (Me.RichTextBox1.TextLength > 0) Then
            'On capture la ligne courante
            Dim NoLigne As Integer = Me.RichTextBox1.GetLineFromCharIndex(Me.RichTextBox1.SelectionStart)
            sArgs = Me.RichTextBox1.Lines(NoLigne)
        End If
        FormOuvrirListe.Reset()
        Dim oMarqueur As ClassMarqueur
        For Each oItem As ListViewItem In Me.ListViewMarqueurs.Items
            If oItem.Checked Then
                oMarqueur = oItem.Tag
                'On boucle sur tous les noms de fichiers complet
                For Each oMatch As System.Text.RegularExpressions.Match In System.Text.RegularExpressions.Regex.Matches(Me.RichTextBox1.Text, oMarqueur.Masque, System.Text.RegularExpressions.RegexOptions.IgnoreCase Or System.Text.RegularExpressions.RegexOptions.Multiline)
                    FormOuvrirListe.AjouterFichierSiExiste(oMatch.Value)
                Next
            End If
        Next
        Dim bOldCaptureMacro As Boolean = Commun.CaptureMacro
        Commun.CaptureMacro = False
        For Each oItem As ListViewItem In FormOuvrirListe.ListView1.CheckedItems()
            OuvrirFichier(oItem.Text)
        Next
        Commun.CaptureMacro = bOldCaptureMacro
        Me.AfficheCourant(oOldItem)
        Me.RichTextBox1.SelectionStart = oOldPos
        Me.RichTextBox1.SelectionLength = oOldLen
        'AjouteHistorique("scpEdit.OuvrirFichiersMarqueurs()")
    End Sub

    Private Sub OuvrirFichiersMarqueurs()
        Dim oOldItem As ListViewItem = oItemCourant
        Dim oOldPos As Integer = Me.RichTextBox1.SelectionStart
        Dim oOldLen As Integer = Me.RichTextBox1.SelectionLength
        Dim sArgs As String = Me.RichTextBox1.SelectedText
        'Si on n'a pas de sélection alors on se rabat sur la ligne courante
        If (sArgs = "") And (Me.RichTextBox1.TextLength > 0) Then
            'On capture la ligne courante
            Dim NoLigne As Integer = Me.RichTextBox1.GetLineFromCharIndex(Me.RichTextBox1.SelectionStart)
            sArgs = Me.RichTextBox1.Lines(NoLigne)
        End If
        FormOuvrirListe.Reset()
        Dim oMarqueur As ClassMarqueur
        For Each oItem As ListViewItem In Me.ListViewMarqueurs.Items
            If oItem.Checked Then
                oMarqueur = oItem.Tag
                'On boucle sur tous les noms de fichiers complet
                For Each oMatch As System.Text.RegularExpressions.Match In System.Text.RegularExpressions.Regex.Matches(Me.RichTextBox1.Text, oMarqueur.Masque, RegexOptions.IgnoreCase Or RegexOptions.Multiline)
                    FormOuvrirListe.AjouterFichierSiExiste(oMatch.Value)
                Next
            End If
        Next
        If FormOuvrirListe.ShowSiFichiers() = Windows.Forms.DialogResult.OK Then
            For Each oItem As ListViewItem In FormOuvrirListe.ListView1.CheckedItems()
                OuvrirFichier(oItem.Text)
            Next
        End If
        Me.AfficheCourant(oOldItem)
        Me.RichTextBox1.SelectionStart = oOldPos
        Me.RichTextBox1.SelectionLength = oOldLen
        AjouterHistoriqueMacro("scpEdit.OuvrirFichiersMarqueurs()")
    End Sub

    Private Sub OuvrirLesFichiersDeLaSélectionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OuvrirLesFichiersDeLaSélectionToolStripMenuItem.Click
        Call OuvrirFichiersSelection()
    End Sub

    Private Sub OuvrirLesFichiersDeLaSélectionToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OuvrirLesFichiersDeLaSélectionToolStripMenuItem1.Click
        Call OuvrirFichiersSelection()
    End Sub

    Private Sub OuvrirLesFichiersDéfinisParLeTexteMarquéToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OuvrirLesFichiersDéfinisParLeTexteMarquéToolStripMenuItem.Click
        Call OuvrirFichiersMarqueurs()
    End Sub

    Private Sub OuvrirLesFichiersIdentifiésParLeTexteMarquéToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OuvrirLesFichiersIdentifiésParLeTexteMarquéToolStripMenuItem.Click
        Call OuvrirFichiersMarqueurs()
    End Sub

    Private Sub OuvrirLesFichiersIdentifiésParLeTexteMarquéToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OuvrirLesFichiersIdentifiésParLeTexteMarquéToolStripMenuItem1.Click
        Call OuvrirFichiersMarqueurs()
    End Sub

    Private Sub FermerSaufCourantToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FermerSaufCourantToolStripMenuItem.Click
        Call Me.FermerTousSaufCourant()
    End Sub

    Private Sub FermerTousToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FermerTousToolStripMenuItem1.Click
        Call Me.FermerTous()
    End Sub

    Private Sub VBScriptToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles VBScriptToolStripMenuItem.Click
        Call Me.InsererCode()
    End Sub

    Private Sub CommandeShellToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CommandeShellToolStripMenuItem.Click
        Call Me.InsererShell()
    End Sub

    Private Sub CommandePowerShellToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CommandePowerShellToolStripMenuItem.Click
        Call Me.InsererPowerShell()
    End Sub

    Private Sub IntersectionDeListesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles IntersectionDeListesToolStripMenuItem.Click
        Call Me.IntersectionListesInteractif()
    End Sub

    Public Sub IntersectionListes(ByVal bSupprimer As Boolean)
        Dim bFirst As Boolean = True
        Dim eInter As IEnumerable(Of String) = Nothing
        Dim oDocument As ClassDocument
        For Each oItem As ListViewItem In Me.ListViewFichiers.Items
            oDocument = oItem.Tag
            If bFirst Then
                eInter = oDocument.Contenu.Split(vbLf)
                bFirst = False
            Else
                eInter = eInter.Intersect(oDocument.Contenu.Split(vbLf))
            End If
        Next
        'Supprimer des fichiers individuels
        If bSupprimer Then
            For Each oItem As ListViewItem In Me.ListViewFichiers.Items
                Me.AfficheCourant(oItem)
                Dim sContenu As String = ""
                For Each item As String In DocumentCourant.Contenu.Split(vbLf)
                    If Not eInter.Contains(item) Then sContenu = Commun.AppendString(sContenu, item, vbLf)
                Next
                Me.RichTextBox1.Text = sContenu
                Call Me.RechercherMarqeursDocCourant()
            Next
        End If
        'Reporter les résultats dans un nouveau document
        Call Me.Nouveau()
        For Each Item As String In eInter
            If Me.RichTextBox1.Text <> "" Then Me.RichTextBox1.AppendText(vbCrLf)
            Me.RichTextBox1.AppendText(Item)
        Next
        AjouterHistoriqueMacro("scpEdit.IntersectionListes " & bSupprimer.ToString)
    End Sub

    Private Sub IntersectionListesInteractif()
        'Faire l'intersection de tous les fichiers ouverts en les traitant comme des listes de lignes
        If Me.ListViewFichiers.Items.Count > 1 Then
            If FormInterListes.ShowDialog = DialogResult.OK Then
                Call IntersectionListes(FormInterListes.CheckBoxSupprime.Checked)
            End If
        Else
            MsgBox("Cette fonction s'applique à deux fichiers ouverts ou plus.", MsgBoxStyle.Exclamation)
        End If
    End Sub

    Private Sub LookupToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LookupToolStripMenuItem1.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Lookup)
    End Sub

    Private Sub LookupToolStripMenuItem2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LookupToolStripMenuItem2.Click
        Call QuickTransform(sender, ClassTextOp.EnumTextOperation.Lookup)
    End Sub

    Private Sub RestreindreAuTexteMarquéToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RestreindreAuTexteMarquéToolStripMenuItem.Click
        Me.RestreindreAuTexteMarqueToolStripMenuItem.Checked = Me.RestreindreAuTexteMarquéToolStripMenuItem.Checked
    End Sub

    Private Sub RestreindreAuTexteMarqueToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles RestreindreAuTexteMarqueToolStripMenuItem.Click
        Me.RestreindreAuTexteMarquéToolStripMenuItem.Checked = Me.RestreindreAuTexteMarqueToolStripMenuItem.Checked
    End Sub

    Private Sub CompterLesFichiersContenantToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CompterLesFichiersContenantToolStripMenuItem.Click
        Call Me.CompterFichiersContenant()
    End Sub

    Private Sub CompterFichiersContenant()
        FormCompteFichiers.ShowDialog()
    End Sub

    Public Function GetTexteMarque(ByVal sFormat As String) As System.Collections.Specialized.StringCollection
        'Tous les documents
        Dim oDoc As ClassDocument
        Dim oMarqueur As ClassMarqueur
        Dim colResult As New System.Collections.Specialized.StringCollection
        For Each oItemDoc As ListViewItem In Me.ListViewFichiers.Items
            oDoc = oItemDoc.Tag
            For Each oItemMarqueur As ListViewItem In Me.ListViewMarqueurs.CheckedItems
                oMarqueur = oItemMarqueur.Tag
                Dim oOption As RegexOptions = RegexOptions.Multiline
                If oMarqueur.SensibleCasse = Boolean.FalseString Then oOption = oOption Or RegexOptions.IgnoreCase
                Dim oRegEx As New Regex(oMarqueur.Masque, oOption)
                For Each oMatch As Match In oRegEx.Matches(oDoc.Contenu)
                    Dim sSortie As String = sFormat
                    If sSortie = "" Then
                        sSortie = oMatch.Value
                    Else
                        For i As Integer = 0 To oMatch.Groups.Count
                            sSortie = sSortie.Replace("$" & i, oMatch.Groups(i).Value)
                        Next
                    End If
                    If sSortie <> "" Then colResult.Add(sSortie)
                Next
            Next
        Next
        Return colResult
    End Function

    Public Function GetTexteExtrait() As System.Collections.Specialized.StringCollection
        'Tous les documents
        Dim oDoc As ClassDocument
        Dim oMarqueur As ClassMarqueur
        Dim colResult As New System.Collections.Specialized.StringCollection
        For Each oItemDoc As ListViewItem In Me.ListViewFichiers.Items
            oDoc = oItemDoc.Tag
            For Each oItemMarqueur As ListViewItem In Me.ListViewMarqueurs.CheckedItems
                oMarqueur = oItemMarqueur.Tag
                Dim oOption As RegexOptions = RegexOptions.Multiline
                If oMarqueur.SensibleCasse = Boolean.FalseString Then oOption = oOption Or RegexOptions.IgnoreCase
                Dim oRegEx As New Regex(oMarqueur.Masque, oOption)
                For Each oMatch As Match In oRegEx.Matches(oDoc.Contenu)
                    Dim sSortie As String = oMarqueur.Modele
                    If sSortie = "" Then
                        sSortie = oMatch.Value
                    Else
                        sSortie = Regex.Replace(sSortie, "\$Fichier", oDoc.Titre, RegexOptions.IgnoreCase)
                        sSortie = Regex.Replace(sSortie, "\$Chemin", oDoc.Chemin, RegexOptions.IgnoreCase)
                        sSortie = Regex.Replace(sSortie, "\$No", oMatch.Index.ToString("0"), RegexOptions.IgnoreCase)
                        For iSubMatch As Integer = 0 To oMatch.Groups.Count - 1
                            sSortie = sSortie.Replace("$" & iSubMatch.ToString("0"), oMatch.Groups(iSubMatch).Value)
                        Next
                    End If
                    If sSortie <> "" Then colResult.Add(sSortie)
                Next
            Next
        Next
        Return colResult
    End Function

    Public Sub InsererFinTag()
        'On analyse le texte qui précède le curseur
        Dim sTexteAvant As String = Me.RichTextBox1.Text.Substring(0, Me.RichTextBox1.SelectionStart)
        'On cherche tous les tags <>
        Dim sTag As String
        Dim sTagPile As String
        Dim Pile As New Collections.Stack()
        Dim oColmatch As System.Text.RegularExpressions.MatchCollection = System.Text.RegularExpressions.Regex.Matches(sTexteAvant, "<(/?[^> ]+)( +[^> ]*)*(?<! /)>", RegexOptions.IgnoreCase Or RegexOptions.Multiline Or RegexOptions.RightToLeft)
        For Each oMatch As System.Text.RegularExpressions.Match In oColmatch
            sTag = oMatch.Groups(1).Value
            If sTag.StartsWith("/") Then
                'On a un tag fermant
                sTag = sTag.Substring(1, sTag.Length - 1)
                'On l'empile
                Pile.Push(sTag)
            Else
                'On a un tag ouvrant
                sTagPile = ""
                If Pile.Count > 0 Then sTagPile = Pile.Peek()
                If sTagPile = sTag Then
                    sTag = Pile.Pop()
                Else
                    'On a un tag ouvrant pas fermé. On le ferme et on à fini
                    Me.RichTextBox1.SelectedText = "</" & sTag & ">"
                    Exit For
                End If
            End If
        Next
        AjouterHistoriqueMacro("scpEdit.InsererFinTagXML()")
    End Sub

    Private Sub FermerDernierTagOuvertToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FermerDernierTagOuvertToolStripMenuItem.Click
        Call Me.InsererFinTag()
    End Sub

    Private Sub CopierEtEnregistrerSousToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopierEtEnregistrerSousToolStripMenuItem.Click
        Call Me.CopierEnregistrerSous()
    End Sub

    Private Sub CopierEnregistrerSous()
        Me.DocumentCourant.Contenu = Me.RichTextBox1.Text
        Me.DocumentCourant.ContenuRTF = Me.RichTextBox1.Rtf
        Dim oDocTemp As ClassDocument = Me.DocumentCourant
        Call Me.Nouveau()
        Me.RichTextBox1.Rtf = oDocTemp.ContenuRTF
        Call Me.EnregistrerSous(Me.DocumentCourant)
        Call Me.AfficherProprietes()
        AjouterHistoriqueMacro("scpEdit.CopierEnregistrerFichierSous(" & Chr(34) & Me.DocumentCourant.Chemin & Chr(34) & ")")
    End Sub

    Private Sub CopierEtEnregistrerSousToolStripMenuItem1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CopierEtEnregistrerSousToolStripMenuItem1.Click
        Call Me.CopierEnregistrerSous()
    End Sub

    Private Sub NuméroterLesLignesSelonIndentationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NuméroterLesLignesSelonIndentationToolStripMenuItem.Click
        QuickTransform(sender, ClassTextOp.EnumTextOperation.Numeroter)
    End Sub

    Private Sub NumeroterLesLignesSelonIdentationToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles NumeroterLesLignesSelonIdentationToolStripMenuItem.Click
        QuickTransform(sender, ClassTextOp.EnumTextOperation.Numeroter)
    End Sub

    Private Sub DenuméroterLesLignesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DenuméroterLesLignesToolStripMenuItem.Click
        QuickTransform(sender, ClassTextOp.EnumTextOperation.Denumeroter)
    End Sub

    Private Sub DénuméroterLesLignesToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DénuméroterLesLignesToolStripMenuItem.Click
        QuickTransform(sender, ClassTextOp.EnumTextOperation.Denumeroter)
    End Sub



    Private Sub ToolStripButton12_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        If Not DocumentCourant Is Nothing Then
            DocumentCourant.Lancer()
        End If
    End Sub

    Private Sub CodeDeCouleurHTMToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CodeDeCouleurHTMToolStripMenuItem.Click
        Call InsererCouleur()
    End Sub

    Private Sub InsererCouleur()
        Dim sCouleur As String = ""
        If Me.RichTextBox1.SelectionLength > 0 Then
            sCouleur = Me.RichTextBox1.SelectedText
            If Not Commun.TestRegex(sCouleur, "#[0-9a-f]{6}") Then sCouleur = ""
        End If
        Me.ColorDialog1.SolidColorOnly = False
        Me.ColorDialog1.AnyColor = True
        Me.ColorDialog1.Color = System.Drawing.ColorTranslator.FromHtml(sCouleur)
        If Me.ColorDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
            AjouterHistoriqueMacro("scpEdit.InsererTexte(" & Chr(34) & System.Drawing.ColorTranslator.ToHtml(Me.ColorDialog1.Color) & Chr(34) & ")")
            Me.RichTextBox1.SelectedText = System.Drawing.ColorTranslator.ToHtml(Me.ColorDialog1.Color)
        End If
    End Sub

    Private Sub CodeDeCouleurHTMLToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CodeDeCouleurHTMLToolStripMenuItem.Click
        Call Me.InsererCouleur()
    End Sub

    Private Sub ToolStripButton12_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripButton12.Click
        If Not DocumentCourant Is Nothing Then
            DocumentCourant.Lancer()
        End If
    End Sub

    Private Sub SupprimerToolStripMenuItem2_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles SupprimerToolStripMenuItem2.Click
        Call SupprimerCourant(Me.DocumentCourant)
    End Sub

    Private Sub ToolStripMenuItem63_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ToolStripMenuItem63.Click
        If Not DocumentCourant Is Nothing Then
            DocumentCourant.Lancer()
        End If
    End Sub

    Private Sub TriDuTexteMarquéToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TriDuTexteMarquéToolStripMenuItem.Click
        Call TrierTexteMarque()
    End Sub

    Public Sub TrierTexteMarque()
        If Not Me.DocumentCourant Is Nothing Then
            For Each oItem As ListViewItem In Me.ListViewMarqueurs.Items
                If oItem.Checked Then
                    Dim oMarqueur As ClassMarqueur = oItem.Tag
                    Me.RichTextBox1.Text = oMarqueur.Tri(Me.RichTextBox1.Text)
                End If
            Next
        End If
        Call Me.RechercherMarqeursDocCourant()
        AjouterHistoriqueMacro("scpEdit.TrierTexteMarque()")
    End Sub

    Private Sub TrierLeTexteMarquéToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TrierLeTexteMarquéToolStripMenuItem.Click
        Call TrierTexteMarque()
    End Sub

    Private Sub InsérerUnTexteValidéParMarqueurToolStripMenuItem1_Click(sender As System.Object, e As System.EventArgs) Handles InsérerUnTexteValidéParMarqueurToolStripMenuItem1.Click
        Call InsererTexteMarqueur()
    End Sub

    Private Sub GuideToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles GuideToolStripMenuItem.Click
        Commun.Guide()
    End Sub

    Private Sub AProposToolStripMenuItem_Click_1(sender As System.Object, e As System.EventArgs) Handles AProposToolStripMenuItem.Click
        AboutBox.ShowDialog()
    End Sub

    Private Sub FermerDernièreBaliseXMLToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles FermerDernièreBaliseXMLToolStripMenuItem.Click
        Call Me.InsererFinTag()
    End Sub
End Class
